MySQL返回同名相同表的联接
我正在使用mysql 我有两张桌子MySQL返回同名相同表的联接,mysql,sql,inner-join,Mysql,Sql,Inner Join,我正在使用mysql 我有两张桌子 Students: stud_num prof1 prof2 Prof prof_id first_name last_name Prof Id是学生表中的外键 我想把stud_num和prof1作为名字和姓氏,prof2作为名字和姓氏 以下是我的查询不起作用: select s.stud_num, CONCAT(p.first_name, " ", p.last_name) as PROF1, CONCAT(p.first_name, " ", p.l
Students:
stud_num
prof1
prof2
Prof
prof_id
first_name
last_name
Prof Id是学生表中的外键
我想把stud_num和prof1作为名字和姓氏,prof2作为名字和姓氏
以下是我的查询不起作用:
select s.stud_num, CONCAT(p.first_name, " ", p.last_name) as PROF1, CONCAT(p.first_name, " ", p.last_name) as PROF2
from students s
inner join prof p
on s.prof1 = p.prof
and s.prof2 = p.prof
这是行不通的。有没有简单的方法可以做到这一点?请尝试以下方法:
SELECT s.stud_num,
CONCAT(p1.first_name, " ", p1.last_name) as PROF1,
CONCAT(p2.first_name, " ", p2.last_name) as PROF2
FROM students s, prof p1, prof p2
WHERE s.prof1 = p1.prof
AND s.prof2 = p2.prof
请尝试以下操作:
SELECT s.stud_num,
CONCAT(p1.first_name, " ", p1.last_name) as PROF1,
CONCAT(p2.first_name, " ", p2.last_name) as PROF2
FROM students s, prof p1, prof p2
WHERE s.prof1 = p1.prof
AND s.prof2 = p2.prof
两次连接到professor表,但如果没有提供professor的ID,我建议使用左连接
select
s.stud_num,
CONCAT(p1.first_name, " ", p1.last_name) as PROF1,
CONCAT(p2.first_name, " ", p2.last_name) as PROF2
from
students s
LEFT join prof p1
on s.prof1 = p1.prof
LEFT join prof p2
on s.prof2 = p2.prof
两次连接到professor表,但如果没有提供professor的ID,我建议使用左连接
select
s.stud_num,
CONCAT(p1.first_name, " ", p1.last_name) as PROF1,
CONCAT(p2.first_name, " ", p2.last_name) as PROF2
from
students s
LEFT join prof p1
on s.prof1 = p1.prof
LEFT join prof p2
on s.prof2 = p2.prof
Prof表需要以两个不同的名称联接两次。 试试这个:
select s.stud_num,
CONCAT(p1.first_name, " ", p1.last_name) as PROF1,
CONCAT(p2.first_name, " ", p2.last_name) as PROF2
from students s,
prof p1,
prof p2
where s.prof1 = p1.prof_id
and s.prof2 = p2.prof_id
Prof表需要以两个不同的名称联接两次。 试试这个:
select s.stud_num,
CONCAT(p1.first_name, " ", p1.last_name) as PROF1,
CONCAT(p2.first_name, " ", p2.last_name) as PROF2
from students s,
prof p1,
prof p2
where s.prof1 = p1.prof_id
and s.prof2 = p2.prof_id
谢谢,完全同意。我只是在发布了它并观看了另一个答案后想了想。谢谢并完全同意。我只是在发布了它并观看了另一个答案后想。谢谢所有的快速回复!!!!感谢所有的快速回复!!!!