mysql NOT与AND组合

nwlls2ji  于 2023-04-28  发布在  Mysql
关注(0)|答案(2)|浏览(213)

我正在尝试从数据库中查询行列表。它有7个字段(列)(A,B,C,VA,VB,VC,LISTED)。

SELECT * FROM datas WHERE 
        ((A=1 OR A IS NULL) AND (B=1 OR B IS NULL) AND (C=1 OR C IS NULL))  -- A/B/C are either 1 or NULL
        AND (VA=1 AND VB=1 AND VC=1)    -- VA/VB/VC must ALL be 1
        AND LISTED=0
        AND NOT (A=1 AND B=1 AND C=1)   -- BUT A/B/C must NOT be ALL 1 (at least one NULL)
ORDER BY ID ASC

一切正常,直到我添加AND NOT行。它不返回行。
为了更简短地解释它,我想检索A/B/C为1或NULL但不是ALL到1的所有行。
并且VA/VB/VC必须都为1。(LISTED为0)
Thanks:)

8fq7wneg

8fq7wneg1#

一切都在工作,直到我添加了AND NOT行。它不返回行。
问题是与NOT predicate 中的null值进行比较。A = 1在A为null时返回null,则NOT (NULL)仍然是NULL。显然这不是你想要的行为。
相反,您可以使用<=>,它执行空安全相等:

SELECT *
FROM data
WHERE 
    COALESCE(A, 1) = 1 AND COALESCE(B, 1) = 1 AND COALESCE(C, 1) = 1 -- A/B/C are either 1 or NULL
    AND VA = 1 AND VB = 1 AND VC = 1 -- VA/VB/VC must ALL be 1
    AND LISTED=0
    AND NOT (A <=> 1 AND B <=> 1 AND C <=> 1)   -- BUT A/B/C must NOT be ALL 1 (at least one NULL)
ORDER BY ID ASC

备注:

  • COALESCE()可用于缩短第一个 predicate
  • AND条件周围的括号是多余的(第二个 predicate )
2ledvvac

2ledvvac2#

在mysql中,比较返回0或1,因此可以求和

SELECT * FROM datas WHERE 
        ((A=1 OR A IS NULL) AND (B=1 OR B IS NULL) AND (C=1 OR C IS NULL))  -- A/B/C are either 1 or NULL
        AND (VA=1 AND VB=1 AND VC=1)    -- VA/VB/VC must ALL be 1
        AND LISTED=0
        AND ((A IS NULL) +( B IS NULL) + ( C IS NULL)) Between 1 and 2

--但A/B/C不能全部为1(至少一个NULL)ORDER BY ID ASC

相关问题