MySQL returning an empty field: CONCAT(nonEmpty1,empty2,nonEmpty3) = NULL

前端 未结 6 1131
攒了一身酷
攒了一身酷 2021-02-19 10:27

I have PHP 5 code accessing a MyISAM table on MySQL 5 server. The query looks like this:

SELECT CONCAT(fName1,\' \',mName2,\' \',lName3) AS userName 
    FROM us         


        
6条回答
  •  无人共我
    2021-02-19 11:25

    you could also the COALESCE() function to return the first non-null value. Like so:

    SELECT CONCAT(fName1,COALESCE(CONCAT(' ',mName2,' '),' '),lName3) AS userName 
      FROM users 
      WHERE level > 10
    

    This would also only put one space if there was no middle name and a space before and after if there was a middle name.

    Reference for this function can be found at: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

提交回复
热议问题