mysql为每个匹配设置一个标志

时间:2009-10-26 07:55:59

标签: sql mysql

我有以下查询:

SELECT users_extra.first_name, users_extra.last_name
FROM (branches, users_extra)
WHERE ((branches.manager_id = users_extra.userid)
OR (branches.sales_manager_id = users_extra.userid)
OR (branches.admin_manager_id = users_extra.userid)
OR (branches.ops_manager_id = users_extra.userid)
OR (branches.export_manager_id = users_extra.userid)
OR (branches.import_manager_id = users_extra.userid))
AND branches.branch_id = [$VAR]

如何为每个匹配返回列名或某种标志,以便我可以返回每个经理的位置,例如:

first_name, last_name, position
joe         soap       manager
john        doe        ops manager

1 个答案:

答案 0 :(得分:1)

您可以在SELECT部分​​中使用CASE WHEN

SELECT users_extra.first_name, users_extra.last_name,
    CASE users_extra.userid
    WHEN branches.manager_id THEN 'manager'
    WHEN branches.sales_manager_id  THEN 'sales manager'
    ...
    END AS position
FROM ...