K
K
kononov9712018-05-03 21:59:52
SQL
kononov971, 2018-05-03 21:59:52

Sampling from two tables in SQL?

Given 2 tables table1 and table2, the fields in them are the same. How to get a selection
of 1. rows that are present in both table1 and table2
2. rows that are unique for each table and do not occur in another?
I tried to use the NOT IN construct, but it didn't work.

SELECT * FROM table1
   WHERE * NOT IN (SELECT * FROM table2);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
alexalexes, 2018-05-04
@alexalexes

There is no specifics about the fields, in the first case it will be so.

select t1.*, t2.*
 from table1 t1
  join table2 t2 on t2.field1 = t1.field1
                       and t2.field2 = t1.field2
                       and ... -- сравниваем все поля

In the second, you need to subtract:
select t1.* from table1 t1
UNION
select t2.* from table2 t2
MINUS
select t1.*
 from table1 t1
  join table2 t2 on t2.field1 = t1.field1
                       and t2.field2 = t1.field2
                       and ... -- сравниваем все поля

P
ponaehal, 2018-06-07
@ponaehal

For the first question, it might work (Depending on the database or SQL standard used):
select t1.* from table1 t1
INTERSECT
select t2.* from table2 t2

C
callback, 2014-05-22
@callback

www.agilecarousel.com

D
dfire, 2014-05-22
@dfire

sorgalla.com/jcarousel

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question