Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Fields of type varchar store sorting of pure numbers

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

If the type of the table field is varchar, but it stores pure numbers, how to sort them according to the size of the numbers?

The following methods are useful for both mysql and oracle

Order by field + 0

Order by field * 1

And so on can be realized.

Mysql > create table tn (id varchar (30), name varchar (50))

Mysql > show create table tn

+- -+

| | Table | Create Table |

+- -+

| | tn | CREATE TABLE `tn` (

`id` varchar (30) DEFAULT NULL

`name` varchar (50) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8 |

Mysql > insert into tn values (1)

Query OK, 1 row affected (0.01sec)

Mysql > insert into tn values (10)

Query OK, 1 row affected (0.00 sec)

Mysql > insert into tn values (11)

Query OK, 1 row affected (0.00 sec)

Mysql > insert into tn values (2)

Query OK, 1 row affected (0.00 sec)

Mysql > insert into tn values (5)

Query OK, 1 row affected (0.00 sec)

Mysql > insert into tn values (3)

Query OK, 1 row affected (0.00 sec)

Mysql > insert into tn values (6)

Query OK, 1 row affected (0.00 sec)

Mysql > select * from tn

+-+ +

| | id | name |

+-+ +

| | 1 | a |

| | 10 | b |

| | 11 | bb |

| | 2 | bb |

| | 5 | c |

| | 3 | f | |

| | 6 | g |

+-+ +

Sort using order by statements

Mysql > select * from tn order by id desc

+-+ +

| | id | name |

+-+ +

| | 6 | g |

| | 5 | c |

| | 3 | f | |

| | 2 | bb |

| | 11 | bb |

| | 10 | b |

| | 1 | a |

+-+ +

7 rows in set (0.00 sec)

It doesn't seem to work, because the value of the id column is of type string.

Resolve:

Use field + 0 to solve

Mysql > select * from tn order by id+0 desc

+-+ +

| | id | name |

+-+ +

| | 11 | bb |

| | 10 | b |

| | 6 | g |

| | 5 | c |

| | 3 | f | |

| | 2 | bb |

| | 1 | a |

+-+ +

7 rows in set (0.00 sec)

Or use field * 1 to solve the problem

Mysql > select * from tn order by id*1 desc

+-+ +

| | id | name |

+-+ +

| | 11 | bb |

| | 10 | b |

| | 6 | g |

| | 5 | c |

| | 3 | f | |

| | 2 | bb |

| | 1 | a |

+-+ +

7 rows in set (0.00 sec)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report