选择和分割一列中的数字,并使用 MySQL 将结果小数显示为整数
让我们首先创建一个表 -
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Number int -> ); Query OK, 0 rows affected (0.50 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable(Number) values(10); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Number) values(20); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Number) values(30); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(Number) values(40); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
输出
这将产生以下输出 -
+----+--------+ | Id | Number | +----+--------+ | 1 | 10 | | 2 | 20 | | 3 | 30 | | 4 | 40 | +----+--------+ 4 rows in set (0.00 sec)
这里有一个使用 MySQL 选择一个整数并进行分割的查询 -
mysql> select Id,Number,(Number/2) AS DivideBy2 from DemoTable;
输出
这将产生以下输出。除法结果为小数值 -
+----+--------+-----------+ | Id | Number | DivideBy2 | +----+--------+-----------+ | 1 | 10 | 5.0000 | | 2 | 20 | 10.0000 | | 3 | 30 | 15.0000 | | 4 | 40 | 20.0000 | +----+--------+-----------+ 4 rows in set (0.00 sec)
如果不希望出现小数值,则使用以下查询并转换为整数 -
mysql> select Id,Number,cast((Number/2) AS UNSIGNED) AS DivideBy2 from DemoTable;
输出
这将产生以下输出 -
+----+--------+-----------+ | Id | Number | DivideBy2 | +----+--------+-----------+ | 1 | 10 | 5 | | 2 | 20 | 10 | | 3 | 30 | 15 | | 4 | 40 | 20 | +----+--------+-----------+ 4 rows in set (0.00 sec)
广告