如何 select 来自两个不同表的不同值
how to select distinct values from two different tables
我有两个 table
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
我想要一个table喜欢...
posid
1
2
即;我想通过加入 table1 和 table2 来获得不同的 "posid",其中 "Mid" 对于 table1 和 table2
你可以这样做:
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);
我想我误解了这个问题。您可以使用 join
:
select t1.posid, t2.posid
from t1 join
t2
on t1.mid = t2.mid;
要将其作为列,您需要逆透视。这是一种方法:
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
我知道您希望两个表的 posid
不同。
这效率不高但有效:
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
您可以将 join
与 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
我有两个 table 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
我想要一个table喜欢...
posid 1 2
即;我想通过加入 table1 和 table2 来获得不同的 "posid",其中 "Mid" 对于 table1 和 table2
你可以这样做:
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);
我想我误解了这个问题。您可以使用 join
:
select t1.posid, t2.posid
from t1 join
t2
on t1.mid = t2.mid;
要将其作为列,您需要逆透视。这是一种方法:
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
我知道您希望两个表的 posid
不同。
这效率不高但有效:
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
您可以将 join
与 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