我有以下查询:
SELECT * FROM thread where sender = 135 or receiver = 135 order by updatedttm desc
上述查询返回具有senderid和receiverid的正确记录。 senderid和receiverid都存在于用户表中。我希望通过将用户表加入上述查询来获取senderid和receiverid的名称。
答案 0 :(得分:5)
您可以join
两次用户表,一次使用发件人ID和接收者ID并获取名称。
SELECT t.*,usend.user_name sender_name, urec.user_name receiver_name
FROM thread t
JOIN users usend on usend.user_id = t.sender
JOIN users urec on urec.user_id = t.receiver
where sender = 135 or receiver = 135
order by updatedttm desc
答案 1 :(得分:0)
我会选择LEFT JOIN
,因为即使发件人或收件人被删除,它也会显示你的帖子。
SELECT *,
sender.username AS sender_name,
receiver.username AS receiver_name
FROM thread AS t
LEFT JOIN users AS sender ON t.sender = sender.user_id
LEFT JOIN users AS receiver ON t.sender = receiver.user_id
WHERE sender = 135 OR receiver = 135
ORDER BY
updatedttm DESC