如何在 MySQL 中強制將列別名設定為特定資料型別?
為此,你可以使用 CASE 語句。我們首先建立一個表 -
mysql> create table DemoTable1505 -> ( -> Value integer unsigned, -> Status tinyint(1) -> ); Query OK, 0 rows affected (0.47 sec)
使用 insert 命令在表中插入一些記錄 -
mysql> insert into DemoTable1505 values(20,0); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1505 values(45,1); Query OK, 1 row affected (0.08 sec)
使用 select 語句顯示錶中的所有記錄 -
mysql> select * from DemoTable1505;
這將產生以下輸出 -
+-------+--------+ | Value | Status | +-------+--------+ | 20 | 0 | | 45 | 1 | +-------+--------+ 2 rows in set (0.00 sec)
以下是強制將列別名設定為特定資料型別的查詢 -
mysql> select case status -> when 0 then cast(Value as signed)*1 -> when 1 then cast(Value as signed)*-1 -> end as AllValues from DemoTable1505;
這將產生以下輸出 -
+-----------+ | AllValues | +-----------+ | 20 | | -45 | +-----------+ 2 rows in set (0.00 sec)
廣告