如何从已知和未知作者的帖子表中获取帖子

时间:2014-06-25 10:59:13

标签: php mysql sql

我在sql中有一个帖子表,其作者列已连接到用户表。我使用单个SQL查询从帖子表中获取帖子,并使用用户表中的作者姓名。我的帖子表格如下:

+----+-----------------+-----------------+--------+
| id | title           | label           | author |
+----+-----------------+-----------------+--------+
| 22 | Post 1          | post-1          |      2 |
| 24 | Post 2          | post-2          |      4 |
| 25 | Post 3          | post-3          |      4 |
| 26 | Post 4          | post-4          |      5 |
| 27 | Post 5          | post-5          |      6 |
| 28 | Post 6          | post-6          |      2 |
| 29 | Post 7          | post-7          |      2 |
| 30 | Post 8          | post-8          |      2 |
| 32 | Post 9          | post-9          |      2 |
+----+-----------------+-----------------+--------+

我使用此sql查询来获取帖子标题,标签及其作者姓名和姓氏。

SELECT `posts`.id, `posts`.title, `posts`.label, users.id AS author, users.name AS name, users.surname AS surname
FROM `posts`
INNER JOIN users
ON users.id = posts.author
ORDER BY `date` DESC;

这完全正常,但它只返回已知作者id为2的帖子,因为在users表中我只有作者ID 2.缺少其他作者(4,5和6)。因此,我没有显示具有未知作者的帖子,而是希望将它们显示为null作为其名称和姓氏变量。顺便说一句,结果是;

+----+----------------+----------------+--------+------+---------+
| id | title          | label          | author | name | surname |
+----+----------------+----------------+--------+------+---------+
| 32 | Post 9         | post-9         |      2 | Jack | Smith   |
| 30 | Post 8         | post-8         |      2 | Jack | Smith   |
| 29 | Post 7         | post-7         |      2 | Jack | Smith   |
| 28 | Post 6         | post-6         |      2 | Jack | Smith   |
| 22 | Post 1         | post-1         |      2 | Jack | Smith   |
+----+----------------+----------------+--------+------+---------+

2 个答案:

答案 0 :(得分:2)

您必须使用LEFT JOIN而不是INNER JOIN。内部联接的结果只显示在两个表中表示的实体。当实体在第一个表中表示而不在第二个表中时,左连接添加空值。

答案 1 :(得分:1)

尝试使用左连接:

再一次创建外键约束,同时引用另一个表值。

SELECT `posts`.id, `posts`.title, `posts`.label, posts.id AS author, 
  users.name AS name, users.surname AS surname
    FROM `posts`
       LEFT JOIN users
          ON users.id = posts.author
             ORDER BY `date` DESC;