我有2张桌子,一个叫A,另一个叫B A与B具有相同的字段
我想做类似的事情
everything In A
and
distinct everything In
A join B on
A.CustomerAccount = B.CustomerAccount
Or A.Email = B.Email
Or (A.CustomerAccount = B.CustomerAccount and A.Email = B.Email)
只是一个简短的说明,还有其他方法吗? (有更有效的方法吗?)
答案 0 :(得分:0)
是的,在这种情况下,最好的解决方案是尝试使用UNION运算符并查看UNION examples。
基本句法-您的查询将代替OR
:
SELECT *
FROM (
SELECT tpl.*, a.MidParentAId as 'MidParentId', 1 as 'IsMidParentA'
FROM TopLevelParent tpl
INNER JOIN MidParentA a ON a.TopLevelParentId = tpl.TopLevelParentID
UNION
SELECT tpl.*, b.MidParentBId as 'MidParentId', 0 as 'IsMidParentA'
FROM TopLevelParent tpl
INNER JOIN MidParentB b ON b.TopLevelParentId = tpl.TopLevelParentID
UNION
SELECT tpl.*, 0 as 'MidParentId', 0 as 'IsMidParentA'
FROM TopLevelParent tpl
WHERE tpl.TopLevelParentID NOT IN (
SELECT pa.TopLevelParentID
FROM TopLevelParent tpl
INNER JOIN MidParentA a ON a.TopLevelParentId = tpl.TopLevelParentID
UNION
SELECT pa.TopLevelParentID
FROM TopLevelParent tpl
INNER JOIN MidParentB b ON h.TopLevelParentId = tpl.TopLevelParentID
)
) tpl
答案 1 :(得分:0)
您似乎想要:
select a.*
from a
union all
select distinct b.*
from b
where exists (select 1
from a
where b.CustomerAccount = a.CustomerAccount or
b.Email = a.Email
);
我删除了条件:
(b.CustomerAccount = a.CustomerAccount and b.Email = a.Email)
因为它是多余的。