Lee Lee - 2 months ago 8
MySQL Question

MySQL - IF within SELECT

I have the following MySQL query:

SELECT id, name, parent_id AS pID,

(SELECT parent_id
FROM category
WHERE id = pID)
AS grandparent_id,

(SELECT parent_id
FROM category
WHERE id = grandparent_id)
AS greatgrandparent_id,

(SELECT name
FROM category
WHERE id = pID)
AS parent,

(SELECT name
FROM category
WHERE id = grandparent_id)
AS grandparent,

(SELECT name
FROM category
WHERE id = greatgrandparent_id)
AS greatgrandparent

FROM category
WHERE active = '1'
HAVING grandparent IS NOT NULL
ORDER BY grandparent_id, parent_id, sort, id ASC


When the
greatgrandparent
IS NULL I want it to display the
grandparent
value instead. Is this possible?

I've tried
CASE WHEN
but must be getting the syntax wrong somewhere as it keeps throwing an error.

Answer

Simple solution: IFNULL(greatgrandparent, grandparent).

Comments