Php 如何从既有已知作者又有未知作者的posts表中获取posts
我在sql中有一个posts表,它的author列连接到users表。我使用一个sql查询从posts表中获取post,并从users表中获取作者姓名。我的posts表如下所示:Php 如何从既有已知作者又有未知作者的posts表中获取posts,php,mysql,sql,Php,Mysql,Sql,我在sql中有一个posts表,它的author列连接到users表。我使用一个sql查询从posts表中获取post,并从users表中获取作者姓名。我的posts表如下所示: +----+-----------------+-----------------+--------+ | id | title | label | author | +----+-----------------+-----------------+--------+ | 22
+----+-----------------+-----------------+--------+
| 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 |
+----+----------------+----------------+--------+------+---------+
您必须使用左连接,而不是内部连接。内部联接的结果只显示在两个表中表示的实体。当实体在第一个表中表示,但在第二个表中不表示时,左联接将添加空值。尝试使用左联接: 还有一种方法是在引用另一个表值时创建外键约束
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;
尝试使用
左连接
而不是内部连接
。为什么在posts表中有非现有用户的作者ID?这很复杂。你看,当我删除一个用户帐户时,我希望他们的帖子保留在posts表中。为什么你要删除用户,而不仅仅是使用一些活动/非活动标志?这不是很好的做法。