2

我有 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_idWHERE

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=1tots=2

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

4

1 回答 1

1

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

编辑

以下语句返回预期结果。您可以在此处
验证这一点(使用 SQL Server)

这样做的要点是

  • 从三个表中选择所有可能的 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 
于 2012-06-20T19:14:52.953 回答