开发者

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.

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. For example, if I have item_id 2, I'd like to get this output:

user_name    item_name    rating_value
Alice        Banana       5
Bob          Banana       2
C开发者_高级运维arol        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:

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.

Edit: Maybe MySQL requires AS for the table aliases.


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..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜