Mysql select non empty column
If the mysql table for the 开发者_运维知识库gallery looks like:
id | pic1 | pic2 | pic3 | pic4
-------------------------------------------------------------
1 | | b.jpg | c.jpg | d.jpg
How can I select the first non empty pic value from columns pic1, pic2, pic3, pic4 for the gallery with id=1?
In example above it will be value from the pic2 column (b.jpg)
SELECT COALESCE(pic1, pic2, pic3, pic4, 'backup.gif') AS pic
FROM gallery
WHERE id = 1
backup.gif
will be returned if all are empty. This also assumed that by empty the columns are NULL.
SELECT COALESCE( pic1, pic2, pic3, pic4 ) AS pic
FROM gallery
WHERE id = 1;
Assuming you used NULL
to represent an empty value, as opposed to blanks
Would be interesting to understand why you are structuring your data in such an inflexible way in the database?
精彩评论