简体   繁体   中英

How to use CASE statement once for multiple columns when the condition is identical?

I have a query like this:

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;

As you see, the condition is identical in all conditions .. So I want to know, can I improve that? I mean can I write CASE just one time for all cases?

Your code is fine. If you really wanted to, you could do:

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)

This gets rid of the CASE statements, but I don't think it is a real simplification. It does, however, reduce the number of times that the condition needs to be copied, which can be a simplification if you have lots of columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM