0

目前我有两个表,约会和用户:

约会ID | 时间 | 教师编号 | 学生卡
1 | 11 | 2 | 1
2 | 12 | 2 | 1

用户 ID | 姓名
1 | 学生
2 | 老师

期望的结果:

约会ID | 时间 | 老师姓名 | 学生姓名
1 | 11 | 老师 | 学生
2 | 12 | 老师 | 学生

基本上我想从约会表中执行 SELECT *,但不是查询给我 id,而是希望名称替换它们。我尝试创建一个临时表和一个 JOIN,但无法弄清楚。任何帮助都会很棒,谢谢!

4

2 回答 2

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

You can check in this SQL Fiddle

于 2013-03-29T21:50:55.100 回答
1

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

DEMO HERE

OUTPUT:

   APPOINTMENT_ID   TIME    TEACHERNAME     STUDENTNAME
          1          11     teacher         student
          2          12     teacher         student
于 2013-03-29T21:56:10.750 回答