简体   繁体   中英

Select from table A and B, where records from table A and table B don't exist in table C?

I'm having trouble visualising the setup for a query I'd like to create.

I have table A (users) and table B (events). For every event, I would like a list of users who did NOT attend.

I imagine a third table is necessary, associating the users with the events, containing both the user and event ID. If a user and event ID combination is absent from the table, the user did not attend.

How would my query need to look in order to return a list of every user who did not attend each event?

Alternatively I could query the events table, loops through the results, and for each event I could query the users who do not have a record with matching event ID in the third table. This seems inefficient and obviously wrong, as many additional db calls are made.

foreach ($getEvents as $v) {
    SELECT userID FROM users WHERE userID NOT IN (SELECT userID FROM tableC WHERE eventID = '".$v["eventID"]."');
}

Happy to provide more information if necessary.

You can handle this by generating all user/event combinations. Then , filter out the ones that do exist:

select e.event_id, u.user_id
from events e cross join
     users u left join
     userevents ue
     on ue.event_id = e.event_id and ue.user_id = u.user_id
where ue.event_id is null;

If you just wanted a list of users who did not attend a single event, we could just left join the users table to the junction table C and be done. However, since you want a report for all events we need a different approach. One option is to use a calendar table which represents every user's relation to every event. We can generate this table via a cross join between the user and event tables. Then, left join this calendar table to the junction table C .

SELECT t1.userID, t1.eventID
FROM
(
    SELECT DISTINCT u.id AS userID, e.id AS eventID
    FROM users u
    CROSS JOIN events e
) t1
LEFT JOIN tableC t2
    ON t1.userID = t2.userID AND
       t1.eventID = t2.eventID
WHERE t2.userID IS NULL;

Try this query !

SELECT
         e.event_id     AS 'Event ID'   , 
         u.user_id      AS 'User ID' 
    FROM
         events         e               ,
         users          u 
    WHERE 
          e.event_id NOT IN (SELECT event_id FROM userevents)
    AND   
          u.user_id  NOT IN (SELECT user_id FROM users)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM