如何在 MySQL 中替换 select 返回的值?

mysqlmysqli database

您可以使用 select case 语句来实现此目的。语法如下。

select yourColumnName1,yourColumnName2,...N,
case when yourColumnName=1 then 'true'
else 'false'
end as anyVariableName
from yourTableName;

为了理解上述语法,让我们创建一个表。创建表的查询如下。

mysql> create table selectReturnDemo
-> (
-> Id int,
-> Name varchar(100),
-> isGreaterthan18 tinyint(1)
-> );
Query OK, 0 rows affected (0.62 sec)

现在您可以使用 insert 命令在表中插入一些记录。查询如下。

mysql> insert into selectReturnDemo values(1,'Carol',0);
Query OK, 1 row affected (0.23 sec)

mysql> insert into selectReturnDemo values(2,'Bob',1);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectReturnDemo values(3,'Mike',1);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectReturnDemo values(4,'David',0);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectReturnDemo values(5,'Adam',1);
Query OK, 1 row affected (0.10 sec)

使用 select 语句显示表中的所有记录。查询如下。

mysql> select *from selectReturnDemo;

以下是输出。

+------+-------+-----------------+
| Id   | Name  | isGreaterthan18 |
+------+-------+-----------------+
| 1    | Carol | 0               |
| 2    | Bob   | 1               |
| 3    | Mike  | 1               |
| 4    | David | 0               |
| 5    | Adam  | 1               |
+------+-------+-----------------+
5 rows in set (0.00 sec)

以下是用 select return 替换值的查询。查询如下。

mysql> select Id,Name,
-> case when isGreaterthan18=1 then 'true'
-> else 'false'
-> end as AgeIsGreaterthan18
-> from selectReturnDemo;

以下是输出。

+------+-------+--------------------+
| Id   | Name  | AgeIsGreaterthan18 |
+------+-------+--------------------+
| 1    | Carol | false              |
| 2    | Bob   | true               |
| 3    | Mike  | true               |
| 4    | David | false              |
| 5    | Adam  | true               |
+------+-------+--------------------+
5 rows in set (0.00 sec)

相关文章