MySQL 查询:使用取模结果对记录排序
为此,请将 ORDER BY 与取模运算符一起使用。让我们首先创建一个表−
mysql> create table DemoTable ( StudentId int, StudentName varchar(100) ); Query OK, 0 rows affected (1.88 sec)
使用 insert 命令将一些记录插入表中−
mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable values(101,'Robert'); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable values(102,'David'); Query OK, 1 row affected (0.94 sec) mysql> insert into DemoTable values(103,'Mike'); Query OK, 1 row affected (0.23 sec)
使用 select 语句显示表中的所有记录−
mysql> select *from DemoTable;
这将产生以下输出−
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 100 | Chris | | 101 | Robert | | 102 | David | | 103 | Mike | +-----------+-------------+ 4 rows in set (0.00 sec)
以下是带有取模运算符的排序查询−
mysql> select StudentId,StudentName,StudentId % 2,StudentId % 3 from DemoTable order by StudentId % 2,StudentId % 3;
这将产生以下输出−
+-----------+-------------+---------------+---------------+ | StudentId | StudentName | StudentId % 2 | StudentId % 3 | +-----------+-------------+---------------+---------------+ | 102 | David | 0 | 0 | | 100 | Chris | 0 | 1 | | 103 | Mike | 1 | 1 | | 101 | Robert | 1 | 2 | +-----------+-------------+---------------+---------------+ 4 rows in set (0.00 sec)
广告