我有3张桌子:
Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)
某些客户记录包含一些带有EventType的CustomerEvent记录,一些客户记录没有CustomerEvent记录。
如何识别/插入每条客户记录的每个EventType缺少的CustomerEvent记录?
我的实际问题比这更详细,但是,这是我努力的部分。
我可以使用一个select语句来识别所有缺少的CustomerEvent记录吗?或者我需要在每个EventType记录上使用UNION吗?
答案 0 :(得分:3)
使用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
)
答案 1 :(得分:0)
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