我有一个使用以下列存储消息的消息传递系统:
我想查询这样的对话:
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中不起作用。有什么建议吗?
答案 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),
);
从性能角度来看,这应该没有区别。