Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Missing Records From Table A For Table B Where They Don't Exist in Table C

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?

like image 918
st0rmyc Avatar asked Nov 24 '25 11:11

st0rmyc


1 Answers

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
    )
like image 89
SqlZim Avatar answered Nov 27 '25 02:11

SqlZim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!