简体   繁体   中英

join 3 tables if 3rd table does not have that value

Table 1

id , userid, eventid , name

table 2

eventid , zoneid , userid

table 3

eventid , userid, status

if all three table having the eventid means i dont want to select that record (i mean if table 3 have the eventid), else i need to select records

i tried my query

SELECT 
    * 
FROM 
    `table1` c1 
    INNER JOIN `table2` c2 ON c2.eventid = c1.eventid  
    LEFT JOIN table3 c3 ON c3.eventid = c1.eventid 
WHERE 
    c2.zoneid=2 
    AND c1.active='1' 
GROUP BY 
    c1.eventid

Add a where clause where there is no c3:

SELECT * 
FROM `table1` c1 
INNER JOIN `table2` c2 ON c2.eventid = c1.eventid  
LEFT JOIN table3 c3 ON c3.eventid = c1.eventid 
WHERE c2.zoneid=2 AND c1.active='1' 
AND c3.id IS NULL
group by c1.eventid 
SELECT 
    * 
FROM 
    `table1` c1 
    INNER JOIN `table2` c2 ON c2.eventid = c1.eventid  
WHERE 
    c2.zoneid=2 
    AND c1.active='1' 
    AND NOT EXISTS (SELECT * FROM table3 c3 WHERE c3.eventid = c1.eventid)
GROUP BY 
    c1.eventid

Applying a WHERE-condition (like some of the other answers suggest) on a table that has been joined through a LEFT/RIGHT OUTER JOIN will actually make it a regular join. The other examples that have been posted ask c1.eventid to equal c3.eventid, and c3.eventid to be NULL - good chance that the result will be not what you expect, depending on how the database treats c1.eventid = c3.eventid if both are NULL (I'd have to read up on that).

A Left join on the 3rd table and the condition WHERE C.eventid IS NULL should do the work.

SELECT * 
FROM   table1 A 
       INNER JOIN table2 B 
                    ON A.eventid = B.eventid 
       LEFT OUTER JOIN table3 C 
                    ON A.eventid = C.eventid 
WHERE  C.eventid IS NULL 

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