选择行不在多列mysql中

时间:2019-06-24 10:25:06

标签: mysql sql where-clause where-in

我有以下结果集:

request_id  |  p_id
66          |  10
66          |  10
66          |  10
66          |  22
66          |  22
76          |  23
76          |  24

我正在尝试选择excludes记录的具有某些组合值的行:

request_id   |   product_id
66           |   10
76           |   23

因此,输出结果集应仅包含以下记录:

66          |  22
66          |  22
76          |  24

我尝试做:

select * from `table` 
where request_id NOT IN (66, 76) AND product_id NOT IN (10, 22)

但这给我空的结果集。

如何仅排除这两个值的组合?

3 个答案:

答案 0 :(得分:5)

您可以在下面尝试-

DEMO

select * from `table` 
where (request_id, p_id) NOT IN ((66, 10),(76,23)) 

输出:

request_id  p_id
66          22
66          22
76          24

答案 1 :(得分:2)

尝试使用类似这样的内容:

SELECT DISTINCT *
FROM TABLE1
WHERE TABLE1.request_id NOT IN
(
    SELECT r_id 
    FROM TABLE2
)
AND TABLE1.p_id NOT IN
(
    SELECT p_id 
    FROM TABLE2
)

答案 2 :(得分:0)

那是一个更好的方法:

SELECT DISTINCT *
FROM TABLE1
LEFT JOIN TABLE2 ON TABLE1.request_id = TABLE2.r_id
                AND TABLE1.p_id = TABLE2.p_id
WHERE TABLE2.p_id IS NULL