一尘不染

MySQL多个IN条件可以使用同一表进行子查询

sql

我有多个IN条件与子查询。

SELECT
    S.name,
    S.email
FROM something S
WHERE 
    1 NOT IN (SELECT id FROM tags WHERE somethingId = S.id)
    AND 2 NOT IN (SELECT id FROM tags WHERE somethingId = S.id)
    AND 3 NOT IN (SELECT id FROM tags WHERE somethingId = S.id)

也许有更好的解决方案?就像是:

    (1, 2, 3) NOT IN (SELECT id FROM tags WHERE somethingId = S.id)

阅读 205

收藏
2021-03-08

共1个答案

一尘不染

重新编写以NOT EXISTS代替使用。即,当某标签中没有某行的somethingId等于s.id并且id为1、2或3时,即从S返回。

SELECT
    S.name,
    S.email
FROM something S
WHERE NOT EXISTS (SELECT 1 FROM tags WHERE id in (1, 2, 3) and somethingId = S.id)

也是NOT EXISTS“ null-safe”。(NOT IN (select returning a null)将完全不返回任何行。)

2021-03-08