【问题标题】:LEFT JOIN show duplicate matchesLEFT JOIN 显示重复的匹配项
【发布时间】:2014-06-25 19:57:06
【问题描述】:

当我左加入这两个表“posts”和“cmets”时:

SELECT *
FROM  `posts` 

+----+-----------+
| id | post_text |
+----+-----------+
|  1 | test0     |
|  2 | test1     |
|  3 | test2     |
|  4 | test3     |
|  5 | test4     |
|  6 | test5     |
|  7 | test6     |
|  8 | test7     |
|  9 | test8     |
| 10 | test9     |
| 11 | test10    |
+----+-----------+

SELECT *
FROM  `comments`

+----+------------------------------------------+---------+
| id |                 comment                  | post_id |
+----+------------------------------------------+---------+
|  1 | hello there                              |       4 |
|  2 | this is another comment on the same post |       4 |
|  3 | this is a comment on a different post    |       7 |
+----+------------------------------------------+---------+

我得到以下信息:

SELECT posts.id, post_id, COUNT( * ) 
FROM posts
LEFT JOIN posts ON posts.id = comments.post_id
GROUP BY posts.id

+----------+---------+----------+
| posts.id | post_id | COUNT(*) |
+----------+---------+----------+
| 4        | 4       | 2        |
| 7        | 7       | 1        |
| ...      | ...     | ...      |
| ...      | ...     | ...      |
+----------+---------+----------+

我想做的是,如果 COUNT(*) 大于 1(意味着帖子上有多个评论),则显示所有匹配的记录,而不是将它们分组为一行,所以它是像这样:

+----------+---------+----------+
| posts.id | post_id | COUNT(*) |
+----------+---------+----------+
| 4        | 4       | 1        |
| 4        | 4       | 1        |
| 7        | 7       | 1        |
| ...      | ...     | ...      |
| ...      | ...     | ...      |
+----------+---------+----------+

【问题讨论】:

  • 只需删除countgroup by。如果还想显示cmets的个数,那就把count(*)改成(select count(1) from comments where post_id = posts.id) as comment_count
  • 太棒了,谢谢伙计。我想我忽略了“GROUP BY”的含义

标签: mysql sql join count


【解决方案1】:

如果删除countgroup by,则可以选择所有记录。为了仍然显示每个帖子的 cmets 数量,您可以使用相关子查询。

另外,我假设您并不想同时显示 posts.idpost_id,因为它们是相同的值,因此以下查询应该更像您的意图:

select posts.id as post_id, comments.id as comment_id, (select count(1) from comments where post_id = posts.id) as comment_count
from posts
left join comments on posts.id = comments.post_id

这是SQL Fiddle demo

【讨论】:

  • 我发现了一个问题 - 当我用 PHP 回显 SQL 时,它会重复值 (post_id: 4),而我只希望它打印一次
  • @user1228907 你的输出应该是什么样子的例子包括两次post_id: 4
  • 好吧,我真的不希望它重复两次,但我可以使用它通过发布的最新评论订购 cmets(使用我已从 cmets 表中排除的时间戳列)
  • 听起来你可能需要重做你的 PHP 逻辑。可能选择所有帖子,然后在特定的帖子视图中,选择按插入日期降序排列的所有 cmets。
  • 我正在尝试选择所有帖子并按最新的 cmets 排序,但是当 COUNT(*) 将它们组合在一起时我不能这样做!
猜你喜欢
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 2012-04-05
  • 2015-04-11
  • 2016-04-25
  • 1970-01-01
  • 2020-09-19
相关资源
最近更新 更多