MySQL 如何在MySQL中强制要求列别名具有特定的数据类型?
为此,您可以使用CASE语句。让我们首先创建一个表 –
mysql> create table DemoTable1505
-> (
-> Value integer unsigned,
-> Status tinyint(1)
-> );
Query OK, 0 rows affected (0.47 sec)
使用插入命令在表中插入一些记录 –
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)
阅读更多:MySQL 教程