带case和when的高级mysql查询

vecaoik1  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(367)

我在一个场景中工作,需要显示列表中不存在id的表中的几个记录。

SELECT * FROM contract 
WHERE `id` NOT IN ( 
    CASE 
        WHEN type = 1 THEN '159,154' 
        WHEN type = 2 THEN '' 
        WHEN type = 3 THEN '' 
    END 
) 
ORDER BY id DESC

在这里您可以看到,如果contract type=1,那么结果不应该显示表中的159&154条记录。但154号的记录也在不该出现的结果中。
感谢您的帮助!

kyxcudwk

kyxcudwk1#

使用mysql instr()函数,如下所示:

SELECT * FROM contract 
WHERE INSTR(IF(type = 1, '159,154',''),`id`)<0
ORDER BY id DESC;
tjvv9vkg

tjvv9vkg2#

...WHERE (type = 1 AND id NOT IN('159','154')) 
OR   (type = 2 AND id !='') 
OR   (type = 3 AND id !='')

如果id是数字,请删除引号,以便可以使用可能的索引。

wb1gzix0

wb1gzix03#

我认为这会奏效:

SELECT * FROM contract 
WHERE (type = 1 AND id NOT IN ('159','154')) OR
    (type IN (2,3) AND id != '')
ORDER BY id DESC

相关问题