有没有更好的方法在MySQL中编写NOT IN(子查询)的东西?

时间:2011-04-28 15:43:17

标签: mysql

有没有更好的方法来写这种东西?

SELECT * from table_a WHERE id NOT IN (SELECT id FROM table_b)

显示here视图比子查询更快,但它不像你可以做SELECT * FROM table_a WHERE id NOT IN view_b,所以我很好奇是否有更好的方式或者这是我们必须忍受的

2 个答案:

答案 0 :(得分:3)

SELECT a.* from table_a a
LEFT JOIN table_b b ON (a.id = b.id)
WHERE b.id IS NULL        

您也可以使用NOT EXISTS(我相信它在mysql中的性能可能稍差):

SELECT a.* from table_a a 
WHERE NOT EXISTS (SELECT 1 FROM table_b b WHERE b.id = a.id)

答案 1 :(得分:2)

派生表:

SELECT  *
FROM    (
        SELECT  id
        FROM    table_b
        ) b
JOIN    table_a a
ON      a.id = b.id

IN谓词无关:

SELECT  *
FROM    table_a
WHERE   id NOT IN
        (
        SELECT  id
        FROM    table_b
        )

IN谓词中的子查询从未实现。

如果您在table_b.id上有索引,这种方式实际上效率最高。

还有两个:

SELECT  *
FROM    table_a a
WHERE   NOT EXISTS
        (
        SELECT  NULL 
        FROM    table_b b
        WHERE   b.id = a.id
        )

SELECT  *
FROM    table_a a
LEFT JOIN
        table_b b
ON      b.id = a.id
WHERE   b.id IS NULL

如果table_b.id无法编入索引(例如,它是派生表达式)且table_a.idUNIQUE,则此查询也可能有效:

SELECT  a.*
FROM    (
        SELECT  id, 1 AS s
        FROM    table_a
        UNION
        SELECT  id, -1 AS s
        FROM    table_b
        ) q
JOIN    table_a a
ON      a.id = q.id
GROUP BY
        a.id
HAVING  MAX(s) = 1

您可能想阅读这篇文章: