Question

I trying to create SQL query with CASE, if field is not null I want to get value from nested SELECT, else I want to my selected field = '-'. If the field is null, then it works, but if not, then I get empty value instead of result of my nested query.

This is my code:

SELECT
    id,
    CASE role
        WHEN 0 THEN \'Handlowiec\'
        WHEN 1 THEN \'Kierownik\'
        WHEN 2 THEN \'Administrator\'
    END AS role,
    name,
    email,
    CASE manager
        WHEN manager IS NULL THEN \'-\'
        ELSE (SELECT name FROM User a WHERE id = manager)
    END AS manager
FROM User ' . $where . ' ORDER BY name

I want to get name of manager or "-" if field "manager" is null.

Was it helpful?

Solution

This could be done with a join instead of nested query:

SELECT
    u.id AS id
    CASE u.role
        WHEN 0 THEN \'Handlowiec\'
        WHEN 1 THEN \'Kierownik\'
        WHEN 2 THEN \'Administrator\'
    END AS role,
    u.name AS name,
    u.email AS email,
    COALESCE (m.name, '-') AS manager
FROM User u
LEFT OUTER JOIN User m ON u.manager = m.id ' . $where . ' ORDER BY name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top