我有一个名为 pages , table_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
这将选择TOP 10 viewed页面,并将仅对这些页面计数项目和投票。
TOP 10 viewed
如果您有很多页面,但只需要10它们,则效率很高,从而消除了不必要的计数。
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。
pages