我正在一个场景中工作,我需要在表中显示列表中不存在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
在这里你可以看到,如果合约类型= 1,那么结果不应显示159&表中的154条记录。但是154号的记录也不会出现在结果中。
任何帮助表示赞赏!
答案 0 :(得分:1)
...WHERE (type = 1 AND id NOT IN('159','154'))
OR (type = 2 AND id !='')
OR (type = 3 AND id !='')
如果id为数字,则删除引号,以便使用可能的索引。
答案 1 :(得分:0)
使用MySQL INSTR() function,如下所示:
SELECT * FROM contract
WHERE INSTR(IF(type = 1, '159,154',''),`id`)<0
ORDER BY id DESC;
答案 2 :(得分:0)
我认为这样可行:
SELECT * FROM contract
WHERE (type = 1 AND id NOT IN ('159','154')) OR
(type IN (2,3) AND id != '')
ORDER BY id DESC