简体   繁体   English

MySQL三表联接,查找项目的等级

[英]MySQL three table join, find item's rating

I'm hoping this is an easy one for you gurus, but my SQL knowledge is failing me. 我希望这对您来说是一个简单的专家,但是我的SQL知识使我失望。

My sample dataset: 我的样本数据集:

item
----
item_id  item_name  item_added
1        Apple      <date_time>
2        Banana     <date_time>

user
----
user_id  user_name
1        Alice
2        Bob
3        Carol

rating
------
rating_id  item_id  user_id  rating_value
1          1        1        3
2          1        2        4
3          1        3        5
4          2        1        5
5          2        2        2

I want to find out what rating all three users have given to a particular item. 我想找出所有三个用户对特定商品的评价。 The output should include NULL for rating_value if the user hasn't rated the item. 如果用户未对商品进行评分,则输出的rating_value应当为NULL。 For example, if I have item_id 2, I'd like to get this output: 例如,如果我有item_id 2,我想得到以下输出:

user_name    item_name    rating_value
Alice        Banana       5
Bob          Banana       2
Carol        Banana       NULL

I've tried all kinds of joins, but I just can't seem to figure this one out. 我已经尝试过各种连接,但是似乎无法弄清楚这个连接。

Many thanks in advance. 提前谢谢了。

It looks like you want a cartesian product of user and item, which will then be joined with rating: 看起来您想要用户和项的笛卡尔积,然后将其与rating结合在一起:

select user_name, item_name, rating_value
from user as u, item as i
left join rating as r
  on r.user_id = u.user_id
 and r.item_id = i.item_id

I haven't done any serious work with MySQL for 4.5 years, but this should do it. 我有4.5年没有对MySQL进行任何认真的工作,但这应该可以做到。

Edit: Maybe MySQL requires AS for the table aliases. 编辑:也许MySQL需要AS为表别名。

select u.user_name, i.item_name, r.rating_value
from item i,user u 
left join rating r
on r.user_id = u.user_id
and r.item_id = i.item_id

This should do the trick.. 这应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM