MySQL select rows where left join is null

后端 未结 6 1378
暗喜
暗喜 2020-12-08 10:02

I have these MySQL tables:

table1:

id | writer
1  | Bob   
2  | Marley
3  | Michael

table2:

user_one | user_two
            


        
6条回答
  •  [愿得一人]
    2020-12-08 10:15

    One of the best approach if you do not want to return any columns from table2 is to use the NOT EXISTS

    SELECT  table1.id 
    FROM    table1 T1
    WHERE
      NOT EXISTS (SELECT *
                  FROM table2 T2
                  WHERE T1.id = T2.user_one
                      OR T1.id = T2.user_two)
    

    Semantically this says what you want to query: Select every row where there is no matching record in the second table.

    MySQL is optimized for EXISTS: It returns as soon as it finds the first matching record.

提交回复
热议问题