0
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 语句。

4

2 回答 2

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
于 2013-09-06T08:41:24.700 回答
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 
于 2013-09-06T08:42:33.373 回答