如何检查两个列中是否存在两个值?

时间:2018-12-14 03:49:11

标签: mysql

我在chat表上有3列,其中id是自动增量主键,而sender_idreceiver_id不是空整数。

id sender_id receiver_id
1  1992      1332
2  1922      1232
3  1232      1211
4  1922      1211
5  1211      1922
6  1922      1211
7  1232      1211
8  1211      1922

现在,我想获得id1922作为发送者或接收者互相交谈的确切1211值。

我尝试过:

select * from chat where sender_id OR receiver_id= 1922

这给了我1922在任一列中的位置,但是我不知道如何检查一行中是否存在两个值!

查询所需的预期输出是ids4,5,6,8

2 个答案:

答案 0 :(得分:0)

那么你可以做:

select * 
from chat 
where (sender_id = 1922 OR sender_id = 1211) OR (receiver_id= 1922 OR receiver_id = 1211)

或:

select * 
from chat 
where sender_id IN (1922,1211) OR receiver_id IN (1922,1211)

答案 1 :(得分:0)

您需要在WHERE子句中具有多个条件的查询。基本上,您需要满足以下条件:

(sender_id = X AND receiver_id = Y) OR (sender_id = Y AND receiver_id = X)

查询可能是这样的:

SELECT
    *
FROM
    chat
WHERE
    (sender_id = 1922 AND receiver_id = 1211)
OR
    (sender_id = 1211 AND receiver_id = 1922)