My sql query to get “posts” along with all tags associated with it:
SELECT
posts.*,
GROUP_CONCAT(tags.tag_name) tags
FROM
posts
LEFT JOIN relation ON relation.post_id = posts.id
LEFT JOIN tags ON tags.tag_id = relation.tag_id
GROUP BY posts.id
(This is only a example code).
If no tags exists, “tags” field will return NULL. How to change this NULL value to empty string ?
We can use SELECT posts.*, IF(ISNULL(GROUP_CONCAT(tags.tag_name)),'',GROUP_CONCAT(tags.tag_name)) AS tags ....
But it GROUP_CONCATs two times. Correct ? What is the best method ?
You can shorten the
ifby using COASLESCEMySQL also supports
IFNULLwhich does the same, but IFNULL only allows 2 parameters, not an unlimited number asCOALESCEdoes.