从2个表中加入3个表,SUM()值(MYSQL)

时间:2013-06-11 21:52:19

标签: mysql sql

我对如何获得 AND 每个项目的投票数量感到困惑。

使用两个简单的JOIN来连接以下3个表,将purchase_count乘以Votes表中的条目数:

SELECT item_id, item_name, sum(backing_status) purchase_count, sum(vote) vote_count 
FROM Items
LEFT JOIN Purchases ON Items.item_id=Purchases.item_id
LEFT JOIN Votes ON Items.item_id=Votes.item_id
where purchase_status='bought' 
group by Items.item_id 

Table Items
item_id item_name
1           item_1
2           item_2
3           item_3

Table Purchases
item_id purchase_status 
1           bought          
2           bought          
1           bought          

Table Votes
item_id    vote 
1           1         
2           1          
3           -1         
1           -1
1           -1 

所需的输出是:

item_id item_name  purchase_count vote_count
1           item_1      2          -1 //sum of -2 downvotes + 1 upvote
2           item_2      1           1
3           item_3      0          -1

我可能需要子查询但不能完全弄清楚查询。或者有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

您应该能够使用以下代码,该代码使用包含两个聚合的子查询来获得结果:

select i.item_id,
  i.item_name,
  coalesce(p.TotalBought, 0)TotalBought,
  coalesce(v.vote_count, 0) vote_count
from items i
left join
(
  select item_id, count(*) TotalBought
  from purchases
  where purchase_status = 'bought'
  group by item_id
) p
  on i.item_id = p.item_id
left join
(
  select item_id, sum(vote) vote_count
  from votes
  group by item_id
) v
  on i.item_id = v.item_id;

SQL Fiddle with Demo

你也可以在没有两个子查询的情况下编写它,但是你需要在JOIN上放置purchase_status的WHERE过滤器:

select i.item_id,
  i.item_name,
  count(p.item_id) TotalBought,
  coalesce(v.vote_count, 0) vote_count
from items i
left join purchases p
  on i.item_id = p.item_id
left join
(
  select item_id, sum(vote) vote_count
  from votes
  group by item_id
) v
  on i.item_id = v.item_id
group by i.item_id, i.item_name;

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

SELECT item_id, item_name, sum(backing_status) AS purchase_count, SUM(vote) 
    AS vote_count
FROM Items i
LEFT JOIN Purchases p on i.item_id = p.item_id
LEFT JOIN (SELECT SUM(vote), item_id FROM votes GROUP BY item_id) AS grv 
    on grv.item_id = i.item_id
WHERE purchase_status='bought';