目前我有两张桌子,约会和用户:
appointment_id | time | teacher_id | student_id 1 | 11 | 2 | 1 2 | 12 | 2 | 1 user_id | name 1 | student 2 | teacher
期望的结果:
appointment_id | time | teachername | studentname 1 | 11 | teacher | student 2 | 12 | teacher | student
基本上我想从约会表中做一个SELECT *,但是不是给我ID的查询,我希望名字替换它们。我尝试过创建一个临时表和一个JOIN,但无法弄明白。任何帮助都会很棒,谢谢!
答案 0 :(得分:2)
这个怎么样?
SELECT
appointment_id,
time,
u.name AS teachername,
v.name AS studentname
FROM
appointments AS a
LEFT JOIN
users AS u ON
a.teacher_id = u.user_id
LEFT JOIN
users AS v ON
a.student_id = v.user_id
您可以查看 SQL Fiddle
答案 1 :(得分:1)
试试这个
select a.appointment_id , a.time ,b.name as teachername ,
c.name as studentname
from appointments a
inner join users b
on a.teacher_id = b.user_id
inner join users c
on a.student_id = c.user_id
输出:
APPOINTMENT_ID TIME TEACHERNAME STUDENTNAME
1 11 teacher student
2 12 teacher student