我有这样的查询:
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
吗?
答案 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
语句,但我不认为这是一个真正的简化。但是,它确实减少了条件需要复制的次数,如果你有很多列,这可以简化。