我有两张桌子: 第一列有以下列:
id
sender
recipient
description
date
,第二列有这些列:
id
name
和发件人和收件人是引用第二个表的ID的外键。
我尝试选择第一个表中的所有行。
SELECT a.id, a.description, b.name as sender, b.name as recipient, a.date FROM table_A a JOIN table_B b WHERE a.sender=b.id AND a.recipient=b.id ORDER BY date DESC
但它只显示sender = recipient的行。如何在每行中显示包含唯一数据的所有行?
答案 0 :(得分:4)
使用LEFT JOIN
代替INNER JOIN
试试这个:
SELECT a.id, a.description, b.name AS sender, c.name AS recipient, a.date
FROM table_A a
LEFT JOIN table_B b ON a.sender = b.id
LEFT JOIN table_B c ON a.recipient = c.id
ORDER BY a.date DESC;