如何在以下SQL查询中使用select Case

时间:2017-04-09 19:25:04

标签: mysql sql phpmyadmin heidisql

我有两张表usersuserdetail。我正在尝试创建一个视图,其中如果userdetail列的状态为1,则应在视图中显示Active,如果状态为0则阻止:

CREATE VIEW `new` AS 
SELECT 
users.id AS id,
userdetail.healthissues AS healthissues,
users.fullName AS fullname,
userdetail.`status`,

 CASE status
 WHEN  userdetail.status ='1' THEN  userdetail.`status`= 'Blocked'
        WHEN  userdetail.status= '0' THEN  userdetail.`status` ='Active'
    END ,

users.phoneNumber AS number
FROM users
JOIN userdetail ON users.id = userdetail.reference

此代码未提供所需结果。有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

我认为这是您想要的正确语法:

CREATE VIEW `new` AS 
    SELECT u.id AS id, ud.healthissues AS healthissues, u.fullName, 
           ud.status as orig_status,
           (CASE WHEN ud.status = 1 THEN 'Blocked'
                 WHEN ud.status = 0 THEN 'Active'
            END) as status,
           u.phoneNumber AS number
    FROM users u JOIN
         userdetail ud
         ON u.id = ud.reference;

注意:

  • 我不确定您是否要选择状态以及字符串,但是您在查询中有这个状态。
  • case的正确语法不使用=,而是使用then子句(除非您希望它返回布尔值)。
  • 表别名使查询更易于编写和阅读。
  • New是视图的错误名称。虽然没有保留,但它是一个关键字。

答案 1 :(得分:0)

您无法指定值..只需选择

即可
CREATE VIEW `new` AS 
SELECT 
users.id AS id,
userdetail.healthissues AS healthissues,
users.fullName AS fullname,
userdetail.`status`,
   CASE status
   WHEN  userdetail.status ='1' THEN  'Blocked'
          WHEN  userdetail.status= '0' THEN 'Active'
      END  as my_eval_status,
users.phoneNumber AS number
FROM users
JOIN userdetail ON users.id = userdetail.reference