我们可以在 MySQL 结果集中用字符串替换数字吗?

mysqlmysqli database

是的,我们可以使用 CASE 语句来做到这一点。让我们首先创建一个表 −

mysql> create table DemoTable
   -> (
   -> isMarried boolean
   -> );
Query OK, 0 rows affected (0.76 sec)

使用 insert 插入命令在表中插入一些记录 −

mysql> insert into DemoTable values(true);
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values(false);
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values(false);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values(true);
Query OK, 1 row affected (0.19 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+-----------+
| isMarried |
+-----------+
| 1         |
| 0         |
| 0         |
| 1         |
+-----------+
4 rows in set (0.00 sec)

以下查询用于在 MySQL 结果集中将数字替换为字符串 −

mysql> select isMarried, CASE isMarried WHEN 1 THEN 'Married' ELSE 'Not Married' END AS Status from DemoTable
-> ;

输出

+-----------+-------------+
| isMarried | Status      |
+-----------+-------------+
| 1         | Married     |
| 0         | Not Married |
| 0         | Not Married |
| 1         | Married     |
+-----------+-------------+
4 rows in set (0.00 sec)


相关文章