简体   繁体   English

在MySQL中使用多个联接和group_concat()?

[英]Using multiple joins and group_concat() in MySQL?

I need to use Joins for a project but I have forgot how to use it. 我需要为项目使用Joins,但是我忘记了如何使用它。 It's all just messing with my head now, I can't quite figure it out. 现在这一切都弄乱了我的头脑,我还不太清楚。

I have five tables, all of which I need to join: 我有五个表,所有这些表都需要加入:

categories - id, name
movies_categories - movie_id, category_id
movies - id, title, description, release_date, cover_image
users - id, username, password
user_movies - user_id, movie_id, favorite, review, watch_date, rating

As you can see the project is movie related, and user_movies contains all the movies the user has watched. 如您所见,该项目与电影有关,并且user_movies包含用户观看过的所有电影。 What I need to do is get all the movies a certain user has watched. 我需要做的是获取特定用户观看的所有电影。 So, I need all of the movie info for each movie, the username (that's pretty much all the info I need from the user), and some of the columns from user_movies (all of them except the first two). 因此,我需要每部电影的所有电影信息,用户名(这几乎是我从用户那里获得的所有信息)以及user_movies的某些列(除了前两个以外的所有列)。 I also need to combine all of the categories for each movies into one "variable". 我还需要将每部电影的所有类别组合为一个“变量”。 I believe you can use GROUP_CONCAT() to do that, I've done it before. 我相信您可以使用GROUP_CONCAT()来做到这一点,我之前已经做过。

It's a tricky task, I really need to get my head around this. 这是一项艰巨的任务,我真的需要努力解决这个问题。 If anyone can help me out I'd appreciate it. 如果有人可以帮助我,我将不胜感激。

If you had provided table schemas (create table scripts) I could test query on sqlfiddle so I couldn't test but I think this query is what you need. 如果您提供了表模式(创建表脚本),则可以在sqlfiddle上测试查询,因此无法测试,但我认为此查询正是您所需要的。

select u.username, u.password
     , um.user_id, um.movie_id, um.favorite
     , um.review, um.watch_date, um.rating 
     , m.movie_title, m.description, m.release_date, m.cover_image
     , mc.category_id
     , group_concat(distinct c.name) as movie_categorynames
from user_movies um
inner join users u on u.id = um.user_id
inner join movies m on m.id = um.movie_id
inner join movies_categories mc on mc.movie_id = um.movie_id
inner join categories c on c.id = mc.category_id
where um.user_id=1
group by um.user_id



USERNAME    PASSWORD    USER_ID MOVIE_ID    FAVORITE    REVIEW  WATCH_DATE  RATING  MOVIE_TITLE DESCRIPTION RELEASE_DATE    COVER_IMAGE CATEGORY_ID MOVIE_CATEGORYNAMES
nike    5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8    1   3   0   This is my movie review!    51351   7   It's Kind of a Funny Story  A clinically depressed teenager gets a new start after he checks himself into an adult psychiatric ward.    2010    8d27232902780886db032afb8d4883a7.jpg    5   Comedy,Drama

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

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