是否有办法将这两个查询合并为一个查询,以便结果为:
ChannelId | ContentType | ContentTypeCount | SumOfAllContentTypes
100 | link | 59 | 179
100 | photo | 49 | 179
100 | status | 2 | 179
100 | video | 4 | 179
101 | link | 15 | 179
101 | status | 50 | 179
以下是我当前使用的查询:
SELECT
COUNT(posts.id)
FROM posts
INNER JOIN channels ON channels.id = posts.channel_id
WHERE channels.site_id = 1003
AND channels.channel_type_id = 1
结果 = 179
和..
SELECT
posts.channel_id,
posts.contenttype,
COUNT(posts.contenttype) as contenttypecount
FROM posts
INNER JOIN channels ON channels.id = posts.channel_id
WHERE channels.site_id = 1003
AND channels.channel_type_id = 1
GROUP BY posts.channel_id, posts.contenttype
结果 = 100 |链接 | 59;等等..
预先感谢您的帮助。
最佳答案
试试这个:
select A.*, B.*
from (
SELECT
posts.channel_id,
posts.contenttype,
COUNT(posts.contenttype) as contenttypecount
FROM posts
INNER JOIN channels ON channels.id = posts.channel_id
WHERE channels.site_id = 1003
AND channels.channel_type_id = 1
GROUP BY posts.channel_id, posts.contenttype
) A
join (
SELECT
COUNT(posts.id) as Total
FROM posts
INNER JOIN channels ON channels.id = posts.channel_id
WHERE channels.site_id = 1003
AND channels.channel_type_id = 1
) B on 1=1
不是特别高效,但简单易行。
关于mysql - SQL:对 COUNT 和 GROUP 求和以合并查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15393798/