如何替换 MySQL 中 select return 的值?


你可以使用 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)

更新于: 30-Jul-2019

991 浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告