将别名名称设置为数据库表字段中的值
Posted
技术标签:
【中文标题】将别名名称设置为数据库表字段中的值【英文标题】:Set Alias Names to Values in a Field of a Database Table 【发布时间】:2013-04-22 19:24:06 【问题描述】:如果我的 mysql 表看起来像这样:
| NAME | STATUS | DESIGNATION |
-------------------------------
| ABCD | 0 | MD |
| DCFG | 1 | CEO |
| AHSG | 1 | DD |
是否可以运行 MySQL 查询以获得如下输出:
| NAME | STATUS | DESIGNATION |
-------------------------------------------
| ABCD | No | Managing Director |
| DCFG | YES | Chief Executive Officer |
| AHSG | YES | Deputy Director |
【问题讨论】:
【参考方案1】:您可以为此使用CASE
声明:
SELECT Name
,CASE Status
WHEN 0 THEN 'No'
WHEN 1 THEN 'YES'
END AS Status
,CASE Designation
WHEN 'MD' THEN 'Managing Director'
WHEN 'CEO' THEN 'Chief Executive Officer'
WHEN 'DD' THEN 'Deputy Director'
END AS Designation
FROM MyTable;
如果您只有两个条件,那么只需使用ELSE
而不是第二个条件:
SELECT Name
,CASE Status
WHEN 0 THEN 'No'
ELSE 'YES' <--- I mean use this instead of WHEN 1 THEN 'YES'
END AS Status
,CASE Designation
WHEN 'MD' THEN 'Managing Director'
WHEN 'CEO' THEN 'Chief Executive Officer'
WHEN 'DD' THEN 'Deputy Director'
END AS Designation
FROM MyTable;
结果:
| NAME | STATUS | DESIGNATION |
-------------------------------------------
| ABCD | No | Managing Director |
| DCFG | YES | Chief Executive Officer |
| AHSG | YES | Deputy Director |
See this SQLFiddle
【讨论】:
对不起,我已经编辑了我的问题..你能根据问题做出答案吗????【参考方案2】:试试这个查询
SELECT Emplyee, if (status = 0, 'No', 'Yes') AS 'Status' from table
已编辑
SELECT
Emplyee,
if (status = 0, 'No', 'Yes') AS 'Status',
CASE Designation
WHEN 'MD' THEN 'Managing Director'
WHEN 'CEO' THEN 'Chief Executive Officer'
WHEN 'DD' THEN 'Deputy Director'
END AS Designation
FROM
table
希望这会有所帮助..
【讨论】:
对不起,我已经编辑了我的问题..你能根据问题做出答案吗????以上是关于将别名名称设置为数据库表字段中的值的主要内容,如果未能解决你的问题,请参考以下文章