数据库
首页 > 数据库> > mysql-ORDER BY UPPER(列)错误

mysql-ORDER BY UPPER(列)错误

作者:互联网

对于MySQL 5.6,给出以下表结构:

mysql> describe groups;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(500) | YES  |     | NULL    |                |
| description | varchar(200) | YES  |     | NULL    |                |
| created_at  | datetime     | YES  |     | NULL    |                |
| updated_at  | datetime     | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

以及以下数据

`groups` table:

mysql> select id, name from groups;
+----+------------------+
| id | name             |
+----+------------------+
|  1 | some-users       |
|  2 | SOME-ADMINS      |
|  3 | customers-group1 |
|  4 | customers-group2 |
|  5 | customers-group3 |
+----+------------------+
5 rows in set (0.00 sec)

以下查询在MySQL中的排序不正确(而该查询至少在PostgreSQL,Oracle和MSSQL中可以正常运行):

mysql> select id, name from groups order by upper(name);
+----+------------------+
| id | name             |
+----+------------------+
|  3 | customers-group1 |
|  4 | customers-group2 |
|  5 | customers-group3 |
|  1 | some-users       |
|  2 | SOME-ADMINS      |
+----+------------------+
5 rows in set (0.00 sec)

我期望:

SOME-ADMINS出现在某些用户之前,其他DB供应商也是如此.

这是MySQL的错误吗?

解决方法:

根据文档,它不区分大小写,但是您可以使用BINARY使其区分大小写:

On character type columns, sorting—like all other comparison operations—is normally performed in a case-insensitive fashion. This means that the order is undefined for columns that are identical except for their case. You can force a case-sensitive sort for a column by using BINARY like so: ORDER BY BINARY col_name.

https://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

标签:mysql-5-6,sql-order-by,sql,mysql
来源: https://codeday.me/bug/20191028/1951468.html