且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL选择左连接为空的行

更新时间:2023-01-20 11:33:42

您可以使用以下查询:

SELECT  table1.id 
FROM    table1 
        LEFT JOIN table2 
            ON table1.id IN (table2.user_one, table2.user_two)
WHERE   table2.user_one IS NULL;

尽管,根据您在table2上的索引,您可能会发现两个联接的效果更好:

Although, depending on your indexes on table2 you may find that two joins performs better:

SELECT  table1.id 
FROM    table1 
        LEFT JOIN table2 AS t1
            ON table1.id = t1.user_one
        LEFT JOIN table2 AS t2
            ON table1.id = t2.user_two
WHERE   t1.user_one IS NULL
AND     t2.user_two IS NULL;