mysql内部连接条件忽略重复的ID
Posted
技术标签:
【中文标题】mysql内部连接条件忽略重复的ID【英文标题】:mysql inner join condition to ignore duplicate ids 【发布时间】:2013-02-27 05:01:03 【问题描述】:在表格列表下方给出。
根据位置 [23,24,25,26,27] 中产品的点击次数总和,按降序排列商店 ID。
给定 product_id = 8
link_shops_locations
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
link_products_shops
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条件与此有关吗? .一点帮助将非常有用。
【问题讨论】:
【参考方案1】:[1]您在 INNER JOIN with products_clicks 中又错过了一个条件。
[2]你也忽略了product_id
。看看这个查询。
[3]您在link_products_shops
表中插入了三次product_id=8 and shop_id=1
。
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
【讨论】:
好吧,我错过了。我现在明白了。但是,我的问题仍然是对于 lcoations 25、26、27 会有重复的 shop_ids,即 3。因此,生成的 SUM(clicks) 乘以 3。如何使其唯一?。 为什么link_products_shops
中有重复的行。删除它们并检查。用小提琴更新了我的查询和答案以上是关于mysql内部连接条件忽略重复的ID的主要内容,如果未能解决你的问题,请参考以下文章