您可以在MySQL中使用CASE语句将键映射到选择查询中单个字段的值。语法如下-
SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N ( CASE WHEN yourColumnName = 1 THEN 'ENABLED' ELSE 'DISABLED' END ) AS anyVariableName FROM yourTableName;
您也可以IF()
出于相同目的使用功能。语法如下-
SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N ,IF(yourColumnName,'ENABLED','DISABLED') as anyVariableName FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table MapKeys -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> isActive boolean, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into MapKeys(Name,isActive) values('Larry',true); mysql> insert into MapKeys(Name,isActive) values('David',false); mysql> insert into MapKeys(Name,isActive) values('Mike',true); mysql> insert into MapKeys(Name,isActive) values('Carol',false); mysql> insert into MapKeys(Name,isActive) values('Sam',false); mysql> insert into MapKeys(Name,isActive) values('Bob',true);
使用select语句显示表中的所有记录。查询如下:
mysql> select *from MapKeys;
以下是输出-
+----+-------+----------+ | Id | Name | isActive | +----+-------+----------+ | 1 | Larry | 1 | | 2 | David | 0 | | 3 | Mike | 1 | | 4 | Carol | 0 | | 5 | Sam | 0 | | 6 | Bob | 1 | +----+-------+----------+ 6 rows in set (0.00 sec)
现在让我们使用case语句映射键。查询如下-
mysql> select Id,Name, -> ( -> CASE WHEN isActive = 1 THEN 'ENABLED' -> ELSE 'DISABLED' -> END -> ) AS Status -> from MapKeys;
以下是输出-
+----+-------+----------+ | Id | Name | Status | +----+-------+----------+ | 1 | Larry | ENABLED | | 2 | David | DISABLED | | 3 | Mike | ENABLED | | 4 | Carol | DISABLED | | 5 | Sam | DISABLED | | 6 | Bob | ENABLED | +----+-------+----------+ 6 rows in set (0.00 sec)
您可以在IF()
方法的帮助下实现相同-
mysql> select Id,Name,if(isActive,'ENABLED','DISABLED') as Status from MapKeys;
以下是输出-
+----+-------+----------+ | Id | Name | Status | +----+-------+----------+ | 1 | Larry | ENABLED | | 2 | David | DISABLED | | 3 | Mike | ENABLED | | 4 | Carol | DISABLED | | 5 | Sam | DISABLED | | 6 | Bob | ENABLED | +----+-------+----------+ 6 rows in set (0.00 sec)