[英]count comments for each row Union and Left Join
请参阅下面的示例数据。
这是我到目前为止所拥有的。
SELECT
table1.stuff,
COUNT(table1.id) AS row_count,
COUNT(comment_table.id) AS comment_count
FROM table1
LEFT JOIN comment_table
ON table1.id = comment_table.page_id
AND comment_table.page_type = 'nofun'
UNION
SELECT
table2.stuff,
COUNT(table2.id) AS row_count,
COUNT(comment_table.id) AS comment_count
FROM table2
LEFT JOIN comment_table
ON table2.id = comment_table.page_id
AND comment_table.page_type = 'fun'
样本数据表1:
id stuff
1 the stuff
2 other stuff
样本数据表2:
id stuff
1 the stuff still
2 other stuff still
样本数据comment_table:
id page_id page_type comment
5 1 fun Ello
6 2 nofun hey janis
所需结果:
stuff comment_count row_count
the stuff still 1 2
other stuff 1 0
样本数据的逻辑:我想返回table1和table2的所有行。 我还想从与表1和表2中的每一行关联的comment_table中获取注释的总数,最后,计算从表1和表2返回的行的总数。
table1和table2具有“ page_type”,在这种情况下,table1是“ nofun”,而table2是“ fun”。 每个comment_table行都通过“ page_type”和“ page_id”(table1或table2的行ID)与table1或table2相关。
table1 id:2有一个注释(comment_table id:6),而table2 id:1有一个注释(comment_table id:5)。
期望的结果表显示了两个样本行,其中有来自table1和table2的'stuff',以及每一行的注释计数以及总行数。
我不相信我完全理解左派。 我如何实现我的目标?
非常感谢@Solarflare指出缺少GROUP BY。
这是我需要的:
SELECT
`table1`.`stuff`,
COUNT(`comment_table`.`id`) AS comment_count
FROM `table1`
LEFT JOIN `comment_table`
ON `table1.id` = `comment_table`.`page_id`
AND `comment_table`.`page_type` = 'nofun'
GROUP BY `table1`.`id`
UNION
SELECT
`table2`.`stuff`,
COUNT(`comment_table`.`id`) AS comment_count
FROM `table2`
LEFT JOIN `comment_table`
ON `table2`.`id` = `comment_table`.`page_id`
AND `comment_table`.`page_type` = 'fun'
GROUP BY `table2`.`id`
数据结果:
stuff comment_count
the stuff still 1
other stuff 1
我删除了“ row_count”,因为数据已正确分组,因此我可以从$ page-> num_rows获取总行数。
感谢所有花时间查看我的问题的人,当然还要感谢那些花时间发表评论的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.