如何选择每个替代行并在SQL中按降序显示?
要获取每个替代行,请MOD()
在WHERE下使用。然后使用ORDERBYDESC以降序显示结果-
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 );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(ClientName,ClientAge) values('Chris',34); mysql> insert into DemoTable(ClientName,ClientAge) values('Tom',45); mysql> insert into DemoTable(ClientName,ClientAge) values('Sam',36); mysql> insert into DemoTable(ClientName,ClientAge) values('Carol',42); mysql> insert into DemoTable(ClientName,ClientAge) values('David',38);
使用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)