MySQL中对varchar类型排序问题_MySQL

WBOY
Release: 2016-06-01 13:28:53
Original
1115 people have browsed it

bitsCN.com

MySQL中对varchar类型排序问题

在今天开发时碰到了这样的一个问题:

在数据库表中有一个对varchar类型的数值进行desc排序,很简单的要求吧。可是奇怪的现象出现了。。表中的数据不会根据从高到底进行排序了。。瞬间有点泪奔的感觉呀。。还好经过高手指点啊。所以想和大家分享一下。。希望下一个mysql初学者以后不要像我一样了啊。。还是废话少说,看代码吧。。

如:有一张T_TESTDEMO表,其有两个DEMOID,DEMONAME字段,其中DEMOID是int类型,DEMONAME是VARCHAR类型但是存放的是认为是数值类型的数据,里面的数据如下:

1,"222222"

2,"33333333"

3,"111111"

4,"2222"

5,"99999"

6,"8888"

7,"11111"

8,"777"

现在有个要求是根据DEMONAME里面的数据从大到小排序,一看很简单的嘛,于是很得意的写下以下SQL:

SELECT * FROM T_TESTDEMO ORDER BY DEMONAME DESC
Copy after login

可是排序的结果是:

5,"99999"

6,"8888"

8,"777"

2,"33333333"

1,"222222"

4,"2222"

3,"111111"

7,"11111"

完全不是想要的那种根据大小排序的,瞬间有点石化啊。所以下面重点来了:

假如使用下面的sql,会是怎样呢?

SELECT * FROM T_TESTDEMO ORDER BY (DEMONAME + 0) DESC ;
Copy after login

排序结果为:

2,"33333333"

1,"222222"

3,"111111"

5,"99999"

7,"11111"

6,"8888"

4,"2222"

8,"777"

呀。好像是想要的那种数据比较大小的了呀。。可是为什么+0就好了呢?

原来,+0后就转换INT类型排序了。这样就可以按照大小排序了。。

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!