我有一条'消息'表格包括列:
message_id, sender_id, receiver_id
一个'成员'表格包括列:
id, username
我的发件箱查询如下
SELECT message_id, username AS 'receiver_username', sender_id,
receiver_id, time_sent, time_read, replied_to_id,item_id_reference,
subject FROM messages, members WHERE messages.sender_id = members.id
AND members.username = ?
我希望我的查询根据发件人message_id
username
WHERE messages.sender_id = members.id AND members.username = ?
以及基于返回的receiver_id
如何在单个查询中执行此操作?
答案 0 :(得分:2)
您需要加入成员表两次,一次是发件人名称,一次是receiver_name。 一个简单的例子:
SELECT
s.user_name sender,
r.user_name receiver
FROM
messages m
JOIN
members s ON
m.sender_id = s.member_id
JOIN
members r ON
m.receiver_id = r.member_id
答案 1 :(得分:0)
这可以是两次加入members
表的替代方法:
SELECT
message_id, username, sender_id,
receiver_id, time_sent, time_read, replied_to_id,item_id_reference,
subject
FROM
messages msg INNER JOIN
members m ON m.id IN (msg.receiver_id, msg.sender_id)
AND m.username = ?