MYSQL SUM()在一个表中,JOIN与另外两个表

时间:2012-06-20 18:48:35

标签: mysql sql join sum

我有3个表:itemspurchasescollaborators。用户可以拥有项目,购买项目或成为项目的协作者。此外,购买的商品可以评为+1或更低,-1。所有者或合作者无法购买自己的物品。

我想获取给定用户的所有项目,并显示每个项目的评分。

这是我的表格:

      items           |           purchases           |     collaborators
i_id  item_id user_id | p_id item_id  user_id  rating |c_id item_id user_id
  1      1       11   |  1      1         13     -1   |  1     1        12 
  2      2       12   |  2      2         11      1   |  2     2        13
  3      3       13   |  3      3         12     NULL |    
                      |  4      1         14     -1   |

到目前为止,这是我的MYSQL查询:

select *, count(p_id) as tots, sum(rating=1) as yes, sum(rating= '-1') as no
from items
left join purchases
on items.item_id=purchases.item_id
left join collaborators
on items.item_id=collaborators.item_id
where items.user_id=13 or purchases.user_id=13 or collaborators.user_id=13
group by items.item_id

以下是我user_id=11的预期结果(在user_id子句中更改每个 WHERE

item_id    tots  yes no
  1         2     0   2
  2         1     1   0
// notice how user_id=11 doesn't have anything to do with item_id=3

以下是user_id=12的预期结果:

item_id    tots  yes no
  1         2     0   2
  2         1     1   0    
  3         1     1   0  

以下是user_id=13的预期结果:

item_id    tots  yes no
  1         2     0   2
  2         1     1   0    
  3         1     1   0   
//notice user_id=13 should have same results as user_id=12. Although, their 
relation to each of the 3 items is different, they still either purchased, 
own, or collaboratored on each of them.

不幸的是,我得到前两个结果,但不是user_id=13的正确结果。 对于user_id=13, item_id=1 tots=1而非tots=2由于某些原因我无法理解。

任何想法,例如“将其分成2个查询更好”,将不胜感激,

1 个答案:

答案 0 :(得分:1)

我仍然不确定我理解你是否正确,但你可以尝试遵循声明,让我们从那里开始工作。

修改

以下语句返回预期结果 You can verify this (using SQL Server) here

这要点是

  • 从三个表中选择所有可能的user_id和item_id组合
  • 选择每个项目的计数/评级
  • 合并结果

SQL声明

SELECT u.user_id, pt.item_id, pt.cnt, pt.yes, pt.no
FROM   (
        SELECT user_id, item_id, title FROM items 
        UNION SELECT user_id, item_id, NULL FROM purchases
        UNION SELECT user_id, item_id, NULL FROM collaborators      
       ) u INNER JOIN (
        SELECT COUNT(*) AS cnt
               , SUM(CASE WHEN ISNULL(rating, 1) = 1 THEN 1 ELSE 0 END) AS yes
               , SUM(CASE WHEN rating =-1 THEN 1 ELSE 0 END) AS no
               , item_id
        FROM   purchases
        GROUP BY
               item_id
      ) pt ON pt.item_id = u.item_id    

MYSQL声明

SELECT u.user_id, pt.item_id, pt.cnt, pt.yes, pt.no, u.title
FROM   (
    SELECT user_id, item_id, title FROM items where user_id=13
    UNION SELECT user_id, item_id, NULL FROM purchases where user_id=13
    UNION SELECT user_id, item_id, NULL FROM collaborators where user_id=13       
   ) u INNER JOIN (
    SELECT COUNT(*) AS cnt
           , SUM(rating=1) AS yes
           , SUM(rating =-1) AS no
           , item_id
    FROM   purchases 
    GROUP BY
           item_id
  ) pt ON pt.item_id = u.item_id