如何在 MySQL SELECT 語句中使用 CAST 函式?
MySQL 中的 CAST() 函式可將任何型別的變數值轉換為指定型別的值。首先讓我們建立一個表 -
mysql> create table castFunctionDemo -> ( -> ShippingDate date -> ); Query OK, 0 rows affected (0.74 sec)
以下是對錶中插入某些記錄的查詢,使用的是插入命令 -
mysql> insert into castFunctionDemo values('2019-01-31'); Query OK, 1 row affected (0.20 sec) mysql> insert into castFunctionDemo values('2018-07-12'); Query OK, 1 row affected (0.16 sec) mysql> insert into castFunctionDemo values('2016-12-06'); Query OK, 1 row affected (0.16 sec) mysql> insert into castFunctionDemo values('2017-08-25'); Query OK, 1 row affected (0.19 sec)
以下是使用 select 語句從表中顯示所有記錄的查詢 -
mysql> select * from castFunctionDemo;
將生成以下輸出 -
+--------------+ | ShippingDate | +--------------+ | 2019-01-31 | | 2018-07-12 | | 2016-12-06 | | 2017-08-25 | +--------------+ 4 rows in set (0.00 sec)
以下是在 MySQL select 語句中正確使用 cast() 函式的查詢 -
mysql> select CAST(ShippingDate AS CHAR(12)) as Conversion FROM castFunctionDemo;
將生成以下輸出 -
+------------+ | Conversion | +------------+ | 2019-01-31 | | 2018-07-12 | | 2016-12-06 | | 2017-08-25 | +------------+ 4 rows in set (0.00 sec)
廣告