如果列值为null,请使用其他列

时间:2013-08-29 13:37:15

标签: mysql sql join csv

首先,不要骂我试图这样做 - 我的老板要我将多个表格中的数据列表转储到一个CSV文件中。

此CSV包含两类人员合并为一张表:永久员工承包商

根据您所属的类别,某些值会有所不同。例如,如果您是承包商,则您的职位描述位于contractors.blended_role。如果您永久,则职位说明位于roles.blended_role roles.id = staff.role

所以我尝试过这样的事情:

SELECT
    stuff,
    (CASE
        WHEN c.blended_role IS NULL THEN
            r.blended_role
        ELSE
            c.blended_role
        END) as `Job Description`,
    morestuff
FROM
    everyone e
LEFT JOIN contractors c
    ON c.id = e.id
LEFT JOIN staff s
    ON s.id = e.id
LEFT JOIN roles r
    ON r.id = s.role

但是我遇到了语法错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'stuff, (CASE WHEN c.blended_role IS NULL THEN r.blended_role EL` at line 2

有人可以提出替代方案吗?

更新

语法错误来自缺少逗号几行。

2 个答案:

答案 0 :(得分:5)

您没有名为rvcv的表别名。也许你的意思是:

SELECT
    (CASE
        WHEN c.blended_role IS NULL THEN
            r.blended_role
        ELSE
            c.blended_role
        END) as `Job Description`

或者更简单:

coalesce(c.blended_role, r.blended_role) . . .

答案 1 :(得分:0)

我认为你也可以使用

SELECT
    stuff,
    ifnull(c.blended_role,r.blended_role) as `Job Description`,
    morestuff
FROM
    everyone e
LEFT JOIN contractors c
    ON c.id = e.id
LEFT JOIN staff s
    ON s.id = e.id
LEFT JOIN roles r
    ON r.id = s.role

查看http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull了解详情。