开发者

How to query multiple tables with a single query

I have three tables: user, friend_recommendation, and movie. I would like to get the name of the person who recommended this movie to me, along with the movie information from the movie table, and the comment in the fri开发者_StackOverflow中文版end_recommendation table. How do I do this?

Assume that user table has name as an attribute, movie table has movie title as an attribute, and friend_recommendation has UID (user who recommends), FID (who is recommended), and COMMENT (what is the comment from UID to FID)

Is it even possible to do this in one query?


So three tables, essentially with these fields (greatly simplified):

users (userId, name)
movies (movieId, movieInfo)
recommendations (fromUserId, toUserId, movieId, comment)

SELECT fromUser.name, toUser.name, m.movieInfo, r.comment
FROM recommendations r
INNER JOIN movies m ON m.movieId = r.movieId
INNER JOIN users fromUser ON r.fromUserId = fromUser.userId
INNER JOIN users toUser ON r.toUserId = toUser.userId
WHERE r.toUserId = << my user id, or whatever your criteria are >>

Edit in response to the comments below: Also retrieving the name/details of the user the movie was recommended to is as simple as joining to the users table again. You can see in the JOINs that we select from users twice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜