在MySQL中选择WHERE子句的所有行

时间:2013-12-26 10:04:55

标签: mysql sql select join left-join

我有两张桌子: 第一列有以下列:

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的行。如何在每行中显示包含唯一数据的所有行?

1 个答案:

答案 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;