带有案例的Sql案例

时间:2013-09-06 08:35:48

标签: mysql sql case

select id, username, email, 
 case
 when username = email then 'true'
 else 'false' 
 end 
 from users

是否有一种简单的方法可以when username = email then 'true' as order_colfrom users where case = true

问题是你可以在AS case中包装案例,然后对其进行排序或使用Where语句。

2 个答案:

答案 0 :(得分:1)

 select id, username, email, 
             case when username = email 
                  then 'true'
                  else 'false' 
             end as usr_is_email
 from users
 order by usr_is_email

答案 1 :(得分:1)

您可以使用ORDER BY中的别名,但不能使用WHERE中的别名,这样可行:

SELECT id, username, email, 
       CASE 
         WHEN username = email THEN 'true' 
         ELSE 'false' 
       end AS UserNameIsEmail 
FROM   users 
ORDER  BY UserNameIsEmail DESC,
          username ASC

如果您希望在WHERE中使用它,请重复它或使用子查询:

SELECT id, username, email, usernameisemail 
FROM  (SELECT id, 
              username, 
              email, 
              CASE 
                WHEN username = email THEN 'true' 
                ELSE 'false' 
              end AS UserNameIsEmail 
       FROM   users)X 
WHERE  X.usernameisemail = 'true' 
ORDER  BY username ASC