简体   繁体   English

MySQL联接三表

[英]MySQL join three table

I have three table 我有三张桌子

table1 表格1

userid  name
1       A
2       B
3       C

table2 表2

trackid     userid  track_des
1           2           123
2           3           234
3           3           345

table3 表3

trackid     description
1               ABC
2               BCD

I want output like this where userid=3 我想要这样的输出,其中userid = 3

userid  name    trackid     description     track_des
3       C       2           BCD             234
3       C       3           NULL            345

I am using MySQL. 我正在使用MySQL。

Your table1 looks to contain users and your table3 looks to contain tracks. 您的table1看起来包含用户,而table3看起来包含轨道。 Your table2 looks like it's a join table describing a many-to-many relationship between users and tracks. 您的table2看起来像是一个联接表,描述了用户和轨道之间的多对多关系。 It seems the join table may contain references to tracks that don't exist in table3 eg. 似乎联接表可能包含对table3不存在的轨道的引用,例如。 trackid 3 . trackid 3 To produce the output you've shown in your example, begin by selecting the records corresponding to userid 3 and join it to table2 (your many-to-many join table). 要产生示例中显示的输出,请首先选择与userid 3对应的记录,然后将其连接到table2 (您的多对多连接表)中。 Next, you should left join to your table containing tracks. 接下来,您应该将联接保留到包含轨道的表中。 You need a left join here because some tracks listed in the join table won't be found but those rows should still be included in the output. 您需要在此处进行左联接,因为将找不到联接表中列出的某些轨道,但这些行仍应包含在输出中。 The only task remaining is specifying the columns you would like returned. 剩下的唯一任务是指定您要返回的列。 Here is what the complete query looks like: 完整的查询如下所示:

select
    u.*,
    ut.trackid,
    t.description,
    ut.track_des
from table1 as u
inner join table2 as ut
    on ut.userid = u.userid
left outer join table3 as t
    on t.trackid = ut.trackid
where u.userid = 3;
select
    t1.*,
    t2.trackid,
    t3.description,
    t2.track_des
from table1 as t1
inner join table2 as t2
    on t2.userid =t1.userid
left join table3 as t3
    on t3.trackid = t2.trackid
where t1.userid = 3;

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

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