如何在 SQL 中选择每个替代行并按降序显示?
mysqlmysqli database
要获取每个替代行,请在 WHERE 下使用 MOD()。然后使用 ORDER BY DESC 按降序显示结果 −
select *from yourTableName where mod(yourColumnName,2)=1 order by yourColumnName DESC;
首先我们创建一个表 −
mysql> create table DemoTable ( UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(40), ClientAge int ); Query OK, 0 rows affected (1.02 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(ClientName,ClientAge) values('Chris',34); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Tom',45); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Sam',36); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Carol',42); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('David',38); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----------+------------+-----------+ | UniqueId | ClientName | ClientAge | +----------+------------+-----------+ | 1 | Chris | 34 | | 2 | Tom | 45 | | 3 | Sam | 36 | | 4 | Carol | 42 | | 5 | David | 38 | +----------+------------+-----------+ 5 rows in set (0.00 sec)
现在让我们选择每个备选行并按降序显示 −
mysql> select *from DemoTable where mod(UniqueId,2)=1 order by UniqueId DESC;
这将产生以下输出 −
+----------+------------+-----------+ | UniqueId | ClientName | ClientAge | +----------+------------+-----------+ | 5 | David | 38 | | 3 | Sam | 36 | | 1 | Chris | 34 | +----------+------------+-----------+ 3 rows in set (0.00 sec)