0

有没有一种方法是将这两个查询合并为一个查询,这样结果是:

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; ETC..

在此先感谢您的帮助。

4

1 回答 1

2

试试这个:

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

不是特别有效,但简单易行。

于 2013-03-13T18:48:08.353 回答