CASE MySQL - SELECT作为值

时间:2014-04-28 00:49:28

标签: mysql sql case nested-queries

我尝试使用CASE创建SQL查询,如果field不为null我想从嵌套SELECT获取值,否则我想要我选择的字段=' - '。如果该字段为null,那么它可以工作,但如果没有,那么我得到空值而不是嵌套查询的结果。

这是我的代码:

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

我想得到经理的姓名或者" - "如果字段"经理"是空的。

1 个答案:

答案 0 :(得分:1)

这可以通过连接而不是嵌套查询来完成:

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