0

我有一列:account_type,其中包含四个字符。d, h, v, a. 现在,如果 account_type 是dthen 它应该显示DBA, if athen application, if vthen vendor, and if hthen human。我试过这个查询。

SELECT da.account_name, da.account_id,da.manager_lastname, da.manager_firstname, 
dap.live_password_change, dap.dev_password_change, das.status_desc, 
REPLACE(RTRIM(CONCAT(IF(da.account_type = 'd', 'DBAs', 'NO'))), ' ', ', ')
FROM dba_account da
LEFT JOIN dba_account_password dap ON da.account_id = dap.account_id
LEFT JOIN dba_account_status das ON da.status = das.status_id
WHERE CAST(da.account_name AS BINARY) RLIKE '[a-z]'
AND da.account_name NOT RLIKE '[#$\\\\////]'
ORDER BY da.account_name

但我不知道如何比较 4 个条件。请问有什么建议吗?

4

3 回答 3

4

您将使用CASE类似于此:

    SELECT da.account_name, da.account_id,da.manager_lastname, da.manager_firstname, 
dap.live_password_change, dap.dev_password_change, das.status_desc, 
CASE da.account_type 
    WHEN 'd' THEN 'DBAs'
    WHEN 'a' THEN 'application'
    WHEN 'v' THEN 'vendor'
    WHEN 'h' then 'human' 
    ELSE 'NO' END as 'account_type'
FROM dba_account da
LEFT JOIN dba_account_password dap ON da.account_id = dap.account_id
LEFT JOIN dba_account_status das ON da.status = das.status_id
WHERE CAST(da.account_name AS BINARY) RLIKE '[a-z]'
AND da.account_name NOT RLIKE '[#$\\\\////]'
ORDER BY da.account_name
于 2012-09-10T22:02:25.433 回答
1

试试CASE 语句。它像switch许多语言一样工作。

于 2012-09-10T21:54:12.377 回答
0

您可以在 SQL 中使用 case 语句,您的查询将被重写如下:

SELECT 
    da.account_name, da.account_id,da.manager_lastname, da.manager_firstname, 
    dap.live_password_change, dap.dev_password_change, das.status_desc, 
    CASE da.account_type\
        WHEN 'd' THEN 'DBAs'
        WHEN 'v' THEN 'vendor'
        WHEN 'h' THEN 'human'
        ELSE 'unknown'
    END
FROM 
    dba_account da LEFT JOIN 
        dba_account_password dap ON da.account_id = dap.account_id 
LEFT JOIN 
    dba_account_status das ON da.status = das.status_id 
WHERE 
    CAST(da.account_name AS  BINARY) RLIKE '[a-z]' 
    AND da.account_name NOT RLIKE '[#$\\\\////]' 
ORDER BY 
    da.account_name;

有关 MySQL 5.6 中 case 语句的更多信息,您可以访问此处: http ://dev.mysql.com/doc/refman/5.6/en/control-flow-functions.html

于 2012-09-10T22:04:47.463 回答