我在下面有mysql查询。但它不起作用。
SELECT CASE
WHEN isLevel = '1' THEN 'Mahasiswa'
WHEN isLevel = '2' THEN 'Dosen'
WHEN isLevel = '3' THEN 'Karyawan'
ELSE 'Admin'
END as level
FROM mhs LEFT JOIN if(isLevel=1,'mahasiswa','dosen') ON username=iduser
WHERE blabala.
如果“isLevel = 1”我想加入mhs和mahasiswa表,如果“isLevel = 2”加入mhs和dosen表,...我应该怎么写查询?
请帮帮我。 感谢。
答案 0 :(得分:1)
您无法有条件地加入。但是使用2个左连接来获取两个表
Select CASE
WHEN isLevel = '1' THEN 'Mahasiswa'
WHEN isLevel = '2' THEN 'Dosen'
WHEN isLevel = '3' THEN 'Karyawan'
ELSE 'Admin'
END as level
from mhs
left join mahasiswa m on m.username=iduser
left join dosen d on d.username=iduser
答案 1 :(得分:1)
您可以在此处使用union语句:
SELECT 'Mahasiswa' AS level
FROM mhs, mahasiswa
WHERE isLevel = 1
AND username = iduser
UNION ALL
SELECT CASE WHEN isLevel = 2 THEN 'Dosen'
WHEN isLevel = 3 THEN 'Karyawan' ELSE 'Admin' END AS level
FROM mhs, dosen
WHERE isLevel != 1
AND username = iduser;
虽然这似乎很难做到。从长远来看,将isLevel列的翻译放入另一个表中可能会更好,因此可以重用。除非你真的很喜欢写CASE语句。