这是我目前得到的:
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
但它不适合我。我不确定如何写这个,以便它可以从两个表中的一个中选择名称。
答案 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