在MySQL varchar字段中可以比较数字吗?

在MySQL varchar字段中可以比较数字吗?

是的,我们可以通过首先使用CAST()来实现。我们首先创建一个表,如下所示:

mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentScore varchar(100)
   -> );
Query OK, 0 rows affected (0.66 sec)

使用插入命令将一些记录插入表中:

mysql> insert into DemoTable(StudentScore) values('90');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(StudentScore) values('100');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(StudentScore) values('56');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(StudentScore) values('98');
Query OK, 1 row affected (0.13 sec)

使用select语句显示表中的所有记录:

mysql> select *from DemoTable;

阅读更多:MySQL 教程

输出

这将产生以下输出:

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
|         1 | 90           |
|         2 | 100          |
|         3 | 56           |
|         4 | 98           |
+-----------+--------------+
4 rows in set (0.00 sec)

以下是在varchar字段中进行比较的查询:

mysql> select *from DemoTable where  CAST(StudentScore AS SIGNED) > 91;

输出

这将产生以下输出:

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
|         2 | 100          |
|         4 | 98           |
+-----------+--------------+
2 rows in set (0.00 sec)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程