[英]Select all data from table while replacing columns with values from another table?
At the moment I have two tables, appointments and users: 目前,我有两个表,约会和用户:
appointment_id | time | teacher_id | student_id 1 | 11 | 2 | 1 2 | 12 | 2 | 1 user_id | name 1 | student 2 | teacher
Desired outcome: 期望的结果:
appointment_id | time | teachername | studentname 1 | 11 | teacher | student 2 | 12 | teacher | student
Basically I want to do a SELECT * from the appointments table, but instead of the query giving me the id's, I want the names to replace them. 基本上,我想从约会表中执行SELECT *,但是我希望名称代替它们,而不是给我ID的查询。 I tried playing around with creating a temporary table and a JOIN but couldn't figure it out.
我试着创建一个临时表和一个JOIN,但无法弄清楚。 Any help would be great, thanks!
任何帮助将是巨大的,谢谢!
What about this? 那这个呢?
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
You can check in this SQL Fiddle 您可以在此SQL Fiddle中签入
try this 尝试这个
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
OUTPUT: 输出:
APPOINTMENT_ID TIME TEACHERNAME STUDENTNAME
1 11 teacher student
2 12 teacher student
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.