在单个SQL语句中使用多个COUNT和SUM

时间:2009-03-06 21:23:12

标签: sql mysql

我有一个名为页面 page_views page_items page_votes 的表格。后三个表包含 page_id 外键,以便保留属于页面的每个单独视图,项目和投票的记录。

当我查询某个页面时,我还要检索 COUNT个page_views COUNT个page_items SUM page_votes.vote

我在下面粘贴了一个查询。它检索总视图数。我已经做了各种尝试来添加项目和投票,但结果是语法错误或者视图/项目/投票返回为相同和“错误”的数字,可能是由于我加入的方式。

如何向此查询添加项目和投票?

SELECT
  Page.*,
  COUNT(*) AS views
FROM pages AS Page 
INNER JOIN page_views AS PageView
  ON Page.id = PageView.page_id 
GROUP BY Page.id 
ORDER BY views DESC   
LIMIT 10 OFFSET 0

2 个答案:

答案 0 :(得分:4)

这将选择TOP 10 viewed个页面,并仅计算这些页面的项目和投票。

如果您有很多页面但只需要10个页面,则效率很高,从而消除了不必要的计数。

SELECT  (
        SELECT COUNT(*)
        FROM   page_views
        WHERE  page_views.page_id = pages.id
        ) AS views_count,
        (
        SELECT COUNT(*)
        FROM   page_items
        WHERE  page_items.page_id = pages.id
        ) AS items_count,
        COALESCE(
        (
        SELECT SUM(vote)
        FROM   page_votes
        WHERE  page_votes.page_id = pages.id
        ), 0) AS votes_sum
FROM    pages
ORDER BY
        views_count DESC
LIMIT 10

更有效的查询:

SELECT  pages.*,
        (
        SELECT COUNT(*)
        FROM   page_items
        WHERE  page_items.page_id = pages.id
        ) AS items_count,
        COALESCE(
        (
        SELECT SUM(vote)
        FROM   page_votes
        WHERE  page_votes.page_id = pages.id
        ), 0) AS votes_sum
FROM    (
        SELECT  page_id, COUNT(*) AS cnt
        FROM    page_views
        GROUP BY
                page_id
        ORDER BY cnt DESC
        LIMIT 10
        ) AS pvd,
        pages
WHERE  pages.id = pvd.page_id

,使用pages消除不需要的联接。

答案 1 :(得分:1)

假设我正确阅读了您的SQL并且您想要按视图排名前10页,请尝试以下方法:

SELECT p.*,
  (SELECT SUM(views) FROM page_views WHERE page_id = p.page_id) views,
  (SELECT SUM(votes) FROM page_votes WHERE page_id = p.page_id) votes,
  (SELECT SUM(items) FROM page_items WHERE page_id = p.page_id) items
FROM pages p
ORDER BY views DESC
LIMIT 10