2

首先,不要因为试图这样做而责骂我——我的老板希望我将许多表中的数据列表转储到单个 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

任何人都可以提出替代方案吗?

更新

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

4

2 回答 2

6

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

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) . . .
于 2013-08-29T13:42:03.420 回答
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了解更多信息。

于 2013-08-29T14:04:14.947 回答