我想知道是否可以在CAS子句中放入CASE语句......在MySQL中? 类似的东西:
SELECT id1 FROM ref_table AS rt WHERE
EXISTS
(SELECT rt.id FROM
(CASE rt.table
WHEN 'tbl1' THEN tbl_1
WHEN 'tbl2' THEN tbl_2
WHEN 'tbl3' THEN tbl_3
END) AS tbl
WHERE tbl.id2 = rt.id_table)
答案 0 :(得分:1)
CASE
表达式的结果不能是表,所以不,你不能使用这种语法。您可以使用OR
(或CASE
)和3个EXISTS
子查询重写查询:
SELECT id1 FROM ref_table AS rt WHERE
CASE rt.table
WHEN 'tbl1' THEN EXISTS (SELECT 1 FROM tbl_1 t WHERE t.id2 = rt.id_table)
WHEN 'tbl2' THEN EXISTS (SELECT 1 FROM tbl_2 t WHERE t.id2 = rt.id_table)
WHEN 'tbl3' THEN EXISTS (SELECT 1 FROM tbl_3 t WHERE t.id2 = rt.id_table)
END ;
更具可读性,OR
:
SELECT id1 FROM ref_table AS rt WHERE
rt.table = 'tbl1' AND EXISTS (SELECT 1 FROM tbl_1 t WHERE t.id2 = rt.id_table)
OR rt.table = 'tbl2' AND EXISTS (SELECT 1 FROM tbl_2 t WHERE t.id2 = rt.id_table)
OR rt.table = 'tbl3' AND EXISTS (SELECT 1 FROM tbl_3 t WHERE t.id2 = rt.id_table)
;