我有以下内容:
SELECT DISTINCT s.username, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.id
)
ORDER BY cnt DESC
基本上我有一个具有以下结构的instagram_item_viewer:
id viewer_id item_id created
它跟踪用户查看项目的时间和时间。所以基本上我想找到看过最多商品的商店。我尝试了上面的查询,它执行得很好,但它似乎没有提供适当的数据,它应该有更多的计数。我做错了什么?
答案 0 :(得分:1)
首先,使用group by语句,您不需要DISTINCT子句。分组负责使您的记录与众不同。
您可能想重新考虑表格的顺序。既然你对商店感兴趣,那就从那里开始吧。
Select s.username, count(v.id)
From instagram_shop s
INNER JOIN instagram_shop_picture p ON p.shop_id = s.shop_id
INNER JOIN instagram_item_viewer v ON v.item_id = p.id
AND v.created >= '2014-08-01'
WHERE s.expirydate IS NULL
AND s.isLocked = 0
GROUP BY s.username
给那个镜头。
答案 1 :(得分:0)
如@Lennart所述,如果您有样本数据,那将会很有帮助。因为否则会有假设。
尝试运行此程序进行调试(这还不是答案)
SELECT s.username, p.id, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.username, p.id
)
ORDER BY cnt DESC
这里的问题是商店和商品查看器相距太远(即通过shop_picture桥接)。因此shop_picture需要在SELECT语句中。
您的原始查询只获得该商店的第一个shop_picture数量,这就是为什么它低于预期
最终,如果您仍想实现目标,可以将我的SQL扩展到
SELECT x.username, SUM(x.cnt) -- or COUNT(x.cnt) depending on what you want
FROM
(
SELECT s.username, p.id, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.username, p.id
)
ORDER BY cnt DESC
) x
GROUP BY x.username