使用临时列进行SELECT,其值基于其他列

时间:2016-05-09 12:20:11

标签: mysql node.js

我有mysql表,其架构类似于下面的json数组。

[
    { "id": 1, "firstName": "Charles Montgomery", "lastName": "Burns", "managerId": 12},
    { "id": 2, "firstName": "Bart", "lastName": "Simpson", "managerId": 1},
    { "id": 3, "firstName": "Marge", "lastName": "Simpson", "managerId": 1},
    { "id": 4, "firstName": "Lisa", "lastName": "Simpson", "managerId": 1},
    { "id": 5, "firstName": "Maggie", "lastName": "Simpson", "managerId": 1},
    { "id": 6, "firstName": "Homer", "lastName": "Simpson", "managerId": 4},
    { "id": 7, "firstName": "Ned", "lastName": "Flanders", "managerId": 4},
    { "id": 8, "firstName": "Krusty", "lastName": "The Clown", "managerId": 2},
    { "id": 9, "firstName": "Waylon", "lastName": "Smithers", "managerId": 2},
    { "id": 10, "firstName": "Ralph", "lastName": "Wiggum", "managerId": 5},
    { "id": 11, "firstName": "Itchy", "lastName": "", "managerId": 5},
    { "id": 12, "firstName": "Comic Book Guy", "lastName": "", "managerId": 4}
]

managerId字段是自引用id字段的外键。

我需要创建一个查询,它将动态添加列,其中“managerName”是从id字段计算出来的,该字段将保存连接的firstName和lastName。

以下是我尝试过的(简化)查询。问号是由mysql driver(在nodejs中)填充的占位符:

SELECT * , 
(SELECT CONCAT_WS(' ', firstName, lastName) FROM employee WHERE managerId = id ) as managerName
FROM employee WHERE employee.id = ?;

我意识到这个WHERE managerId = id是值得关注的地方,但老实说我不知道​​要匹配正确值的条件。

有人可以帮忙吗?

修改 万一有人偶然发现同样的事情,我发现helpful article。即使是相似的例子。

1 个答案:

答案 0 :(得分:2)

LEFT JOIN是你的朋友。 tra使用这样的查询:

SELECT 
    e.*,
    CONCAT_WS(' ', m.firstName, m.lastName) AS managerName
FROM employee e WHERE e.employee.id = ?
LEFT JOIN  employee m ON e.managerId = m.id;