3

I have 3 tables:

Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)

Some Customer records have some CustomerEvent records with an EventType, some Customer records have no CustomerEvent records.

How do I identify/insert missing CustomerEvent records of each EventType for each Customer record?

My actual issue is a bit more detailed than that, however, this is the piece I'm struggling with.

Can I use one select statement to identify all missing CustomerEvent records? Or would I need to UNION on each EventType record?

Chris Albert
  • 2,462
  • 8
  • 27
  • 31
st0rmyc
  • 33
  • 3

2 Answers2

3

Using cross join to generate a set of all CustomerId, EventTypeId and filtering out those that exist in CustomerEvent with 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
    )
SqlZim
  • 37,248
  • 6
  • 41
  • 59
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
Chains
  • 12,541
  • 8
  • 45
  • 62