我有一个带有marital_status字段的用户表,其值为0-5:
(0-单
1,结婚
2-离异
3,丧偶
4-关系)
我正在尝试对此表运行一个select查询,并输出marital_status字段的相应值而不是数字。
这是我正在使用的查询:
SELECT user_id,user_first_name, user_last_name,user_email_1,IF(user_gender="0","Male","Female") AS user_gender,
user_birthdate,
CASE WHEN user_marital_status=0 THEN "Single" END AS user_marital_status, CASE WHEN user_marital_status = 1 THEN "Married" END AS user_marital_status,
CASE WHEN user_marital_status=2 THEN "Divorced" END AS user_marital_status, CASE WHEN user_marital_status = 3 THEN "Widowed" END AS user_marital_status,
CASE WHEN user_marital_status = 4 THEN "In a relationship" END AS user_marital_status
FROM users a
但是,当我运行此查询时,它为user_marital_status创建了5个不同的列 如何让marital_status只是一个具有不同值的列?
答案 0 :(得分:1)
您需要一个包含多个case
子句的when
子句:
SELECT user_id,
user_first_name,
user_last_name,
user_email_1,
IF(user_gender="0","Male","Female") AS user_gender,
user_birthdate,
CASE user_marital_status
WHEN 0 THEN 'Single'
WHEN 1 THEN 'Married'
WHEN 2 THEN 'Divorced'
WHEN 3 THEN 'Widowed'
WHEN 4 THEN 'In a relationship'
END AS user_marital_status
FROM users a