SQL检查是否A和B IN(...)

时间:2017-05-06 23:50:32

标签: mysql sql select

我有一个使用以下列存储消息的消息传递系统:

  • 消息,这是实际消息
  • to_id,即将收到消息的用户的ID
  • from_id,发送消息的用户的ID

我想查询这样的对话:

SELECT sender.username, message
FROM messages
JOIN users sender ON sender.id=messages.from_id
JOIN users receiver ON receiver.id=messages.to_id
WHERE (sender.username LIKE 'user1' AND receiver.username LIKE 'user2')
OR (receiver.username LIKE 'user1' AND sender.username LIKE 'user2')

有效,但我只想传递 user1 user2 一次,例如

WHERE (from_id, to_id) IN ((SELECT id FROM users WHERE username LIKE 'user1'),
(SELECT id FROM users WHERE username LIKE 'user2'))

在mysql中不起作用。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您可以使用元组执行此操作:

SELECT sender.username, message
FROM messages m JOIN
     users sender
     ON sender.id = m.from_id JOIN
     users receiver
     ON receiver.id = m.to_id
WHERE ('user1', 'user2') in ( (sender.username, receiver.username), 
                              (receiver.username, sender.username), 
                            );

从性能角度来看,这应该没有区别。