ashleh
ashleh

Reputation: 225

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. I tried playing around with creating a temporary table and a JOIN but couldn't figure it out. Any help would be great, thanks!

Upvotes: 0

Views: 75

Answers (2)

fedorqui
fedorqui

Reputation: 290185

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

Upvotes: 2

echo_Me
echo_Me

Reputation: 37253

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

Upvotes: 1

Related Questions