如何替換 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)
廣告