【发布时间】:2020-11-11 06:38:29
【问题描述】:
我有 3 个表要加入。
条目表
| entry_id | entry_title |
|----------|----------------------------|
| 1 | Hello World! |
| 2 | Lorem Ipsum Dolor Sit Amet |
| 3 | Foo Title Foo Title |
评论表
| comment_id | comment_content | comment_entry_id |
|------------|-----------------------|------------------|
| 1 | lorem ipsum is great! | 1 |
| 2 | foo is great! | 1 |
| 3 | Hello World! | 2 |
| 4 | Hello Word! | 3 |
threaded_comment 表
| threaded_comment_id | threaded_comment_content | threaded_comment_comment_id |
|---------------------|--------------------------|-----------------------------|
| 1 | i agree foo! | 2 |
| 2 | Yes Foo! | 2 |
| 3 | Lorem Ipsum is great! | 1 |
| 4 | Ah yes, Hello World! | 4 |
这里有一些关于它的信息:
-
comment_entry_id列是comment表到entries表的非标识外键 -
threaded_comment_comment_id列是threaded_comment表到comment表的非标识外键
我想在每个条目中都有总 cmets 和线程 cmets, 所以我这样做了:
SELECT entries.entry_title AS entry_title,
COUNT(comment.comment_id) AS total_of_comments,
COUNT(threaded_comment.threaded_comment_id) AS total_of_threaded_comments,
COUNT(comment.comment_id) + COUNT(threaded_comment.threaded_comment_id) AS total_of_comments_and_threaded_comments
FROM entries
LEFT JOIN comment
ON entries.entry_id = comment.comment_entry_id
LEFT JOIN threaded_comment
ON threaded_comment.threaded_comment_comment_id = comment.comment_id
GROUP BY entries.entry_id
这就是我得到的
| entry_title | total_of_comments | total_of_threaded_comments | total_of_comments_and_threaded_comments |
|----------------------------|-------------------|----------------------------|-----------------------------------------|
| Hello World | 2 | 1 | 3 |
| Lorem Ipsum Dolor Sit Amet | 2 | 2 | 4 |
| Foo Title Foo Title | 1 | 0 | 1 |
如您所见,在“Lorem Ipsum Dolor Sit Amet”行中,我得到了 2 个 total_of_comments,而我只有 1 条评论,其中包含 2 个线程 cmets。
我知道发生这种情况是因为我没有 GROUP BY 和 comment.comment_id,所以当其中有超过 1 个线程评论时,它会重复相同的 comment.comment_id。
所以我的问题是,当我在查询中已经有 1 个 GROUP BY 语句时,如何使用多个 GROUP BY 语句?或者我可以在LEFT JOIN 查询中使用GROUP BY 语句吗?
提前致谢。
【问题讨论】:
-
也许你需要简单的
COUNT(DISTINCT column)?这会将许多相同的列值折叠到1。 -
我同意@Akina,我不能完全理解你想要什么,但很确定
count distinct是答案。
标签: mysql sql database relational-database