MySql - 加入 2 个表,其中第二个表连接了两次

Posted

技术标签:

【中文标题】MySql - 加入 2 个表,其中第二个表连接了两次【英文标题】:MySql - Joining 2 Tables where 2nd table is joined twice 【发布时间】:2016-11-05 20:00:48 【问题描述】:

我有 2 个表(学生班和用户)

表学生班级

columns (id, class_name, user_schoolid_faculty, user_schoolid_student)

表用户

columns (id, firstname, lastname, schoolid, position)

user_schoolid_faculty is a foreign key from schoolid

user_schoolid_student is a foreign key from schoolid

我的第一个查询是

 SELECT * FROM studentclass WHERE class_name = '$class_name'

我想用schoolid查看用户名和姓的数据

 SELECT studentclass.class_name, user.firstname, user.lastname
 FROM studentclass
 INNER JOIN user
 ON studentclass.user_schoolid_faculty = user.schoolid
 WHERE user.position = 'Faculty'
 LEFT JOIN user
 ON studentclass.user_schoolid_student = user.schoolid
 WHERE user.position = 'Student'

这会引发错误,而不是唯一的表/别名“用户”

【问题讨论】:

为什么不使用别名? Aliasses 减少了查询的复杂性。 SELECT a.class_name, b.firstname, b.lastname FROM studentclass as a INNER JOIN [user] as b ON b.user_schoolid_faculty = a.schoolid WHERE a.position = 'Faculty' LEFT JOIN user ON b.user_schoolid_student = a.schoolid WHERE a.position = 'Student' 【参考方案1】:

对于 SQL Server,使用方括号作为保留关键字 user。 还要为表添加别名。

SELECT SC.class_name, U1.firstname, U2.lastname
FROM studentclass SC
INNER JOIN [user] U1 ON SC.user_schoolid_faculty = U1.schoolid
LEFT JOIN [user] U2  ON SC.user_schoolid_student = U2.schoolid AND U2.position = 'Student'
WHERE U1.position = 'Faculty'   

对于 mysql

SELECT SC.class_name, U1.firstname, U2.lastname
FROM studentclass SC
INNER JOIN `user` U1 ON SC.user_schoolid_faculty = U1.schoolid
LEFT JOIN `user` U2  ON SC.user_schoolid_student = U2.schoolid AND U2.position = 'Student'
WHERE U1.position = 'Faculty'   

【讨论】:

谢谢! =) 我用这个 SELECT SC.class_name, U1.firstname, U1.lastname, U2.firstname, U2.lastname FROM studentclass SC INNER JOIN user U1 ON SC.user_schoolid_faculty = U1.schoolid LEFT JOIN user U2 ON SC .user_schoolid_student = U2.schoolid AND U2.position = 'Student' WHERE U1.position = 'Faculty' 它找到了我需要的东西 =)【参考方案2】:

对于同一张表user,你应该使用不同的别名,当你使用JOIN时,你应该使用ON来合并两个表,而不是WHERE,试试这个;)

SELECT studentclass.class_name, user1.firstname, user2.lastname
FROM studentclass
INNER JOIN user user1
ON studentclass.user_schoolid_faculty = user1.schoolid
AND user1.position = 'Faculty'
LEFT JOIN user user2
ON studentclass.user_schoolid_student = user2.schoolid
AND user2.position = 'Student'

还有一个不清楚的地方,你为什么在这个查询中使用一个INNER JOIN和一个LEFT JOIN

【讨论】:

【参考方案3】:

你必须为你的表使用别名:

SELECT studentclass.class_name, u1.firstname, u1.lastname
FROM studentclass
 INNER JOIN user u1
 ON studentclass.user_schoolid_faculty = u1.schoolid
 WHERE user.position = 'Faculty'
 LEFT JOIN user u2
 ON studentclass.user_schoolid_student = u2.schoolid
 WHERE u1.position = 'Student'

【讨论】:

以上是关于MySql - 加入 2 个表,其中第二个表连接了两次的主要内容,如果未能解决你的问题,请参考以下文章

使用 Ajax 未更新第二个表

mysql用总和加入3个表给出错误的结果

如果第二个表不存在连接,Mysql 使用一个表中的列值

根据第二个表中列 y 的最大值连接列 x 上的 2 个表

大查询:加入第二个表中的单个最新行

Laravel 连接 2 个表,第一个表中的一个数据和第二个表中的多行