2

如果我有一个看起来像这样的 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 |
4

2 回答 2

5

您可以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 |

看到这个 SQLFiddle

于 2013-04-29T07:34:59.180 回答
4

试试这个查询

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

希望这可以帮助..

于 2013-04-29T07:33:44.063 回答