当条件相同时,如何对多列使用CASE语句一次?

时间:2016-08-14 15:16:24

标签: php mysql sql case

我有这样的查询:

SELECT (CASE WHEN subject = '' THEN $subject ELSE subject END ) main_subject,
       (CASE WHEN subject = '' THEN $id ELSE id END ) main_id,
       (CASE WHEN subject = '' THEN $related ELSE related END ) main_related
FROM qanda
WHERE tag = :tag;

如您所见,条件在所有条件下都是相同的。所以我想知道,我可以改进吗?我的意思是我可以为所有情况只写一次CASE吗?

1 个答案:

答案 0 :(得分:2)

你的代码很好。如果你真的想,你可以这样做:

SELECT $subject as main_subject, $id as main_id, $related as main_related
FROM qanda
WHERE tag = :tag AND subject = ''
UNION ALL
SELECT subject as main_subject, id as main_id, related as main_related
FROM qanda
WHERE tag = :tag AND (subject <> '' or subject IS NULL)

这摆脱了CASE语句,但我不认为这是一个真正的简化。但是,它确实减少了条件需要复制的次数,如果你有很多列,这可以简化。