问题
I have two tables like table1:
id name posId Mid 1 sam 1 10 2 sid 1 10 3 jeet 1 10
table2:
id name posid Mid 1 Anin 2 10 2 Nir 2 10 3 jeev 2 10
I want to have a table like...
posid 1 2
ie; i want to have distinct "posid" by joining table1 and table2 where "Mid" will be same for table1 and table2
回答1:
You can do something like this:
select distinct t1.posId
from t1
where not exists (select 1 from t2 where t2.posId = t1.posId)
union all
select distinct t2.posId
from t2
where not exists (select 1 from t1 where t2.posId = t1.posId);
I think I misinterpeted the question. You can use join
:
select t1.posid, t2.posid
from t1 join
t2
on t1.mid = t2.mid;
To get this as a column, you need to unpivot. Here is one method:
select distinct (case when n.which = 1 then t1.posid else t2.posid end) as posid
from t1 join
t2
on t1.mid = t2.mid cross join
(select 1 as which union all select 2 as which) n
回答2:
You can use join
with union
select t1.posid
from t1 join t2 on t1.mid = t2.mid
union
select t2.posid
from t1 join t2 on t1.mid = t2.mid
回答3:
I understand you want distinct posid
from both tables.
This isnt efficient but works:
select distinct aa.posid
from
(select distinct table1.posid as posid
from table1
join table2
on table1.mid=table2.mid
UNION ALL
select distinct table2.posid as posid
from table1
join table2
on table1.mid=table2.mid) aa
来源:https://stackoverflow.com/questions/49732525/how-to-select-distinct-values-from-two-different-tables