从一个表中选择真实的IF条件,从另一个表中选择FALSE?

时间:2016-05-15 00:27:31

标签: mysql sql select

这是我目前得到的:

SELECT *, CASE WHEN chat.user_type = 's'
  THEN (SELECT name FROM students WHERE students . id = chat . user_id) AS name
  ELSE (SELECT name FROM teachers WHERE teachers . id = chat . user_id) AS name
FROM chat WHERE classroom_id = '2' ORDER BY timestamp ASC

但它不适合我。我不确定如何写这个,以便它可以从两个表中的一个中选择名称。

1 个答案:

答案 0 :(得分:5)

SELECT *, CASE WHEN chat.user_type = 's'
               THEN students.name
               ELSE teachers.name 
          END AS name
FROM chat 
LEFT JOIN students ON students.id = chat.user_id
LEFT JOIN teachers ON teachers.id = chat.user_id
WHERE classroom_id = '2' 
ORDER BY timestamp ASC

SELECT *, coalesce(students.name, teachers.name) AS name
FROM chat 
LEFT JOIN students ON students.id = chat.user_id AND chat.user_type = 's'
LEFT JOIN teachers ON teachers.id = chat.user_id AND chat.user_type = 't'
WHERE classroom_id = '2' 
ORDER BY timestamp ASC

另见this great explanation of joins