首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从posts表中获得包含已知作者和未知作者的帖子

如何从posts表中获得包含已知作者和未知作者的帖子
EN

Stack Overflow用户
提问于 2014-06-25 10:59:13
回答 2查看 91关注 0票数 1

我在sql中有一个posts表,它的author列连接到用户表。我使用一个sql查询从 post 表获得post,从 use 表获得作者的姓名。我的posts表如下所示:

代码语言:javascript
复制
+----+-----------------+-----------------+--------+
| 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标题、标签及其作者名称和姓氏。

代码语言:javascript
复制
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作为其名称和姓氏变量。顺便说一下,结果是;

代码语言:javascript
复制
+----+----------------+----------------+--------+------+---------+
| 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   |
+----+----------------+----------------+--------+------+---------+
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-25 11:30:36

尝试使用左联接:

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

代码语言:javascript
复制
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;
票数 1
EN

Stack Overflow用户

发布于 2014-06-25 11:07:02

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24406812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档