用if选择查询

时间:2012-09-10 21:52:13

标签: mysql select if-statement

我有一个专栏:account_type,其中包含四个字符。 dhva。现在,如果account_type为d,那么它应显示DBAa然后applicationv然后vendor,以及{ {1}}然后h。我试过了这个问题。

human

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

尝试CASE statement。它在许多语言中都像switch一样。

答案 2 :(得分: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