如何在 MySQL 中为某个单独字段中的键映射值?
在 MySQL 中,可以使用 CASE 语句将键映射到 select 查询中的单个字段的值。语法如下:
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) -> ); Query OK, 0 rows affected (0.65 sec)
使用插入命令在表中插入一些记录。查询如下:
mysql> insert into MapKeys(Name,isActive) values('Larry',true); Query OK, 1 row affected (0.13 sec) mysql> insert into MapKeys(Name,isActive) values('David',false); Query OK, 1 row affected (0.16 sec) mysql> insert into MapKeys(Name,isActive) values('Mike',true); Query OK, 1 row affected (0.14 sec) mysql> insert into MapKeys(Name,isActive) values('Carol',false); Query OK, 1 row affected (0.17 sec) mysql> insert into MapKeys(Name,isActive) values('Sam',false); Query OK, 1 row affected (0.15 sec) mysql> insert into MapKeys(Name,isActive) values('Bob',true); Query OK, 1 row affected (0.19 sec)
使用 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)
广告