mysql - SQL:对 COUNT 和 GROUP 求和以合并查询

标签 mysql sql select count sum

是否有办法将这两个查询合并为一个查询,以便结果为:

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/

相关文章:

mysql - 如何从同一个表的两列中获得一行中不同的结果?

php - MySQL SUM() 一个 ID(User) 的列的所有值 & echo total

sql - 艰难地学习 SQL - 练习 3 - 插入数据 - 找不到文件

sql - 使用 group by 进行选择查询

mysql - 如何使我的 SELECT 查询更有效率?

php - SQL 查询 ID 号以逗号分隔的列?

mysql - 计算表中的行数

php - Yii模型()方法findBySQL( 'SELECT MAX(id) FROM ee_car_types;');

mysql - 为每个不同的列值选择第一行

python - 根据列对某些行赋予权重