【发布时间】:2014-06-25 10:59:13
【问题描述】:
我在 sql 中有一个 posts 表,它的 author 列连接到 users 表。我使用单个 sql 查询从 posts 表中获取帖子,并从 users 表中获取作者姓名。我的 posts 表如下所示:
+----+-----------------+-----------------+--------+
| 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 的帖子,因为在用户表中我只有作者 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 |
+----+----------------+----------------+--------+------+---------+
【问题讨论】:
-
尝试使用
LEFT JOIN而不是INNER JOIN。为什么您的 posts 表中有不存在的用户的作者 ID? -
这很复杂。你看,当我删除一个用户帐户时,我希望他们的帖子保留在帖子表中。
-
你为什么要删除用户而不只是使用一些活动/非活动标志?这不是很好的做法。