我在sql中有一个posts表,它的author列连接到用户表。我使用一个sql查询从 post 表获得post,从 use 表获得作者的姓名。我的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查询获取post标题、标签及其作者名称和姓氏。
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,因为在用户表中,我只有author 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 |
+----+----------------+----------------+--------+------+---------+发布于 2014-06-25 11:30:36
尝试使用左联接:
另外,这会创建外键约束,同时引用另一个表值。
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;发布于 2014-06-25 11:07:02
而不是内部连接,您必须使用左联接。内部联接的结果只是显示在两个表中表示的实体。当实体在第一个表中表示而不是在第二个表中表示时,左联接将添加一个空值。
https://stackoverflow.com/questions/24406812
复制相似问题