mysql内连接导致乘法
基本上我有这样的结构:
- 交易有并属于许多渠道
- 交易有很多 DealSales
- 交易属于渠道
当我想查找交易销售的金额时,我使用这个查询:
SELECT targets.id,SUM(deal_sales.amount_sold) AS amount_sold
FROM deal_sales
INNER JOIN deals ON deals.id = deal_sales.deal_id
INNER JOIN targets ON deals.target_id = targets.id
WHERE targets.approved = 1 AND targets.active = 1
GROUP BY targets.id
它工作得很好,问题是当我需要时按渠道过滤,查找渠道中交易的销售金额:
SELECT targets.id,SUM(deal_sales.amount_sold) AS amount_sold
FROM deal_sales
INNER JOIN deals ON deals.id = deal_sales.deal_id
INNER JOIN targets ON deals.target_id = targets.id
**INNER JOIN channels_deals ON channels_deals.deal_id = deals.id**
WHERE targets.approved = 1 AND targets.active = 1
GROUP BY targets.id
当我将联接添加到渠道表时,amount_sold 会乘以与交易相关的每个渠道。我怎样才能避免这种情况?
basically i have this structure:
- Deal has and belongs to many Channels
- Deal has many DealSales
- Deal belongs to Channel
When i want to find the amount sold by a deal, i use this query:
SELECT targets.id,SUM(deal_sales.amount_sold) AS amount_sold
FROM deal_sales
INNER JOIN deals ON deals.id = deal_sales.deal_id
INNER JOIN targets ON deals.target_id = targets.id
WHERE targets.approved = 1 AND targets.active = 1
GROUP BY targets.id
its working just fine, the problem is when i need to filter by channel, find the amount sold by a deal in a channel:
SELECT targets.id,SUM(deal_sales.amount_sold) AS amount_sold
FROM deal_sales
INNER JOIN deals ON deals.id = deal_sales.deal_id
INNER JOIN targets ON deals.target_id = targets.id
**INNER JOIN channels_deals ON channels_deals.deal_id = deals.id**
WHERE targets.approved = 1 AND targets.active = 1
GROUP BY targets.id
When i add the join to channels table, the amount_sold is multiplied by each channel a deal has relation with. How can i avoid this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 IN 或 Exists
例如
Use IN or Exists
for example