[英]Find Missing Records From Table A For Table B Where They Don't Exist in Table C
我有3张桌子:
Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)
某些Customer记录包含一些带有EventType的CustomerEvent记录,某些Customer记录没有CustomerEvent记录。
如何识别/插入每个Customer记录的每个EventType的缺少CustomerEvent记录?
我的实际问题比这更详细,但是,这是我正在努力的部分。
我可以使用一个select语句来识别所有缺少的CustomerEvent记录吗? 或者我需要在每个EventType记录上使用UNION吗?
使用cross join
生成一组所有CustomerId, EventTypeId
并过滤掉CustomerEvent
中存在的那些not exists()
select c.CustomerId, e.EventTypeId
from Customer c
cross join EventType e
where not exists (
select 1
from CustomerEvent ce
where c.CustomerId = ce.CustomerId
and e.EventTypeId = ce.EventTypeId
)
select * from
CUSTOMEREVENT CE
left join CUSTOMER C ON C.CustomerID = CE.CustomerID
left join EVENTTYPE ET ON CE.EventTypeID = ET.EventTypeID
where
C.CustomerID IS NULL
OR ET.EventTypeID IS NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.