在MySQL中按最后3个字符排序?

您可以使用ORDER BYRIGHT()函数在MySQL中按最后3个字符排序。语法如下-

SELECT *FROM yourTableName

ORDER BY RIGHT(yourColumnName,3) yourSortingOrder;

只需将“ yourSortingOrder”替换为ASC或DESC即可分别设置升序或降序。

为了理解上述语法,让我们创建一个表。创建表的查询如下-

mysql> create table OrderByLast3Chars

   -> (

   -> EmployeeId int NOT NULL AUTO_INCREMENT,

   -> EmployeeName varchar(20),

   -> EmployeeAge int,

   -> PRIMARY KEY(EmployeeId)

   -> );

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Carol_901',24);

mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Bob_101',21);

mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Sam_107',22);

mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('Mile_677',26);

mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('John_978',27);

mysql> insert into OrderByLast3Chars(EmployeeName,EmployeeAge) values('David_876',29);

使用select语句显示表中的所有记录。查询如下-

mysql> select *from OrderByLast3Chars;

以下是输出-

+------------+--------------+-------------+

| EmployeeId | EmployeeName | EmployeeAge |

+------------+--------------+-------------+

| 1          | Carol_901    | 24          |

| 2          | Bob_101      | 21          |

| 3          | Sam_107      | 22          |

| 4          | Mile_677     | 26          |

| 5          | John_978     | 27          |

| 6          | David_876    | 29          |

+------------+--------------+-------------+

6 rows in set (0.00 sec)

这是按最后3个字符排序的查询。

情况1-按升序获取结果。

查询如下-

mysql> select *from OrderByLast3Chars

   -> order by RIGHT(EmployeeName,3) asc;

以下是输出-

+------------+--------------+-------------+

| EmployeeId | EmployeeName | EmployeeAge |

+------------+--------------+-------------+

|          1 | Carol_901    |          24 |

|          2 | Bob_101      |          21 |

|          3 | Sam_107      |          22 |

|          4 | Mile_677     |          26 |

|          5 | John_978     |          27 |

|          6 | David_876    |          29 |

+------------+--------------+-------------+

6 rows in set (0.00 sec)

情况2-按降序获取结果。查询如下-

mysql> select *from OrderByLast3Chars

   -> order by RIGHT(EmployeeName,3) desc;

以下是输出-

+------------+--------------+-------------+

| EmployeeId | EmployeeName | EmployeeAge |

+------------+--------------+-------------+

|          5 | John_978     |          27 |

|          1 | Carol_901    |          24 |

|          6 | David_876    |          29 |

|          4 | Mile_677     |          26 |

|          3 | Sam_107      |          22 |

|          2 | Bob_101      |          21 |

+------------+--------------+-------------+

6 rows in set (0.00 sec)

以上是 在MySQL中按最后3个字符排序? 的全部内容, 来源链接: utcz.com/z/331018.html

回到顶部