2

下面给出了表格列表。

根据位置 [23,24,25,26,27] 中产品的点击次数总和,按降序排列商店 ID。

给定 product_id = 8


链接商店位置

shop_id | location_id
---------------------
1       | 23
2       | 24
3       | 25
3       | 26
3       | 27

products_clicks

shop_id | product_id | clicks
-----------------------------
1       | 8          | 1
2       | 7          | 3
2       | 8          | 87
3       | 8          | 21
3       | 8          | 9

链接产品商店

product_id | shop_id
---------------------
 7         | 1
 8         | 1
 8         | 1
 8         | 2
 8         | 2
 8         | 1
 7         | 3
 8         | 3

这是我尝试过的,

SELECT SUM(c.clicks) as no,
       s.shop_id
FROM  link_products_shops l
INNER JOIN products_clicks c
ON c.product_id = l.product_id
INNER JOIN link_shops_locations s
ON s.shop_id = c.shop_id // duplicate shop_ids gives wrong SUM
WHERE s.location_id IN (23,24,25,26,27)
GROUP BY s.shop_id
ORDER BY no DESC;

我的问题是,由于 link_shops_locations 表有 3 个 shop_id,因此预期的 SUM 乘以 3。我该如何解决这个问题?link_shops_locations 的 INNER JOIN 条件与此有关吗?一点帮助将非常有用。

4

1 回答 1

0

[1]您在使用 products_clicks 的 INNER JOIN中又错过了一个条件。

[2]你也忽略了product_id。看看这个查询。

[3]您在表格中插入product_id=8 and shop_id=1了 3 次。link_products_shops

    select shop_id, SUM(NoOfClicks) FROM(SELECT distinct c.shop_id, c.clicks AS NoOfClicks 
FROM  products_clicks c 
INNER JOIN link_products_shops l 
ON c.product_id = l.product_id 
AND c.shop_id = l.shop_id 
INNER JOIN link_shops_locations s 
ON s.shop_id = c.shop_id and s.shop_id = l.shop_id 
WHERE s.location_id IN (23,24,25,26,27) 
AND c.product_id = 8) AS TabShopCounters
GROUP BY shop_id
ORDER BY NoOfClicks DESC;

SQL 小提琴 - http://www.sqlfiddle.com/#!2/b22fe/8

于 2013-03-11T20:59:15.277 回答