所以我有两张桌子:
的网页:
id page visit_id
1 6 65
2 7 65
3 2 66
4 10 67
访问:
id flipbook
65 april
66 april
67 may
我想返回每个翻书的浏览页数:
april: 3
may: 1
我的查询如下:
"SELECT a.flipbook, (SELECT count(b.page) from pages b WHERE a.id = b.visit_id) AS total FROM visits a GROUP BY a.flipbook"
但它返回:
april: 1
may: 1
因为它只从4月份开始访问,我们访问了一页。
有什么想法吗?
答案 0 :(得分:2)
select a.flipbook, count(*)
from visits a
inner join pages p
on a.id = p.visit_id
group by a.flipbook
不需要子查询 - 这只是一个基本的连接和聚合。
答案 1 :(得分:1)
尝试使用像这样的查询
SELECT a.flipbook,COUNT(*) AS total
FROM visits a
LEFT JOIN pages b ON a.id = b.visit_id
GROUP BY a.flipbook
答案 2 :(得分:1)
SELECT v.flipbook
, COUNT(*) pages_viewed
FROM visits v
JOIN pages p
ON visit_id = v.id
GROUP
BY v.flipbook;
如果你想要' 0'使用OUTER JOIN并计算其他内容。结果也是。
答案 3 :(得分:1)
你可以尝试使用这样的查询:
SELECT v.flipbook, COUNT(*) AS total
FROM pages p
LEFT JOIN visits v ON p.visit_id=v.id
GROUP BY v.flipbook