简体   繁体   中英

MySQL concat select only if condition is valid

let's assume I've a table with these columns:

DATA1 | DATA2 | DATA3

I want to print: DATA1 (DATA2) if DATA2 is not null, only DATA1 if DATA2 is null. If I do it with a concat:

SELECT CONCAT(DATA1," (",COALESCE(DATA2,""),")")

I've the problem that "(" and ")" are always printed, even if DATA2 is null, so I'll have as result: DATA1 () instead of DATA1

Is there any way to do this with sql on mysql database?

You've already got half the answer there. CONCAT will yield NULL if any of the values are null. You're using COALESCE so your entire result isn't null if DATA2 is, so simply include the "()" inside the coalesce.

Try this

SELECT CONCAT(
              DATA1,
              COALESCE(
                         CONCAT(" (",DATA2,")")
                       ,"")
              )

You can use simple CASE:

SELECT CONCAT( DATA1, CASE WHEN DATA2 IS NULL THEN "" ELSE CONCAT( "( ", DATA2, " )" ) END ) 
FROM sometable;

尝试

SELECT IF(DATA2 IS NOT NULL, CONCAT(DATA1, ' (', DATA2, ')'), DATA1) AS data;

You can use UNION statement to merge two result set. First result set will fetch data where DATA2 is null and in other result set will have DATA2 as null.

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