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 JOINuser
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 个表,其中第二个表连接了两次的主要内容,如果未能解决你的问题,请参考以下文章