使用MySQL限制后再获得另一个订单?
您需要将子查询与select语句一起使用,一个用于内部查询,一个用于外部查询。内部选择将返回行,外部选择将按升序排序。语法如下:
SELECT *FROM ( SELECT *FROM yourTableName ORDER BY yourColumnName1 DESC LIMIT 9 ) AS anyAliasName ORDER BY yourColumnName2;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table OrderByAfterLimit -> ( -> Id int NOT NULL AUTO_INCREMENT, -> UserName varchar(20), -> UserAge int, -> PRIMARY KEY(Id) -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下:
mysql> insert into OrderByAfterLimit(UserName, UserAge) values('John',23); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('Larry',21); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('Bob',26); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('James',22); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('Robert',28); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('Mike',29); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('Carol',24); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('David',20); mysql> insert into OrderByAfterLimit(UserName, UserAge) values('Maxwell',30);
使用select语句显示表中的所有记录。查询如下:
mysql> select *from OrderByAfterLimit;
以下是输出:
+----+----------+---------+ | Id | UserName | UserAge | +----+----------+---------+ | 1 | John | 23 | | 2 | Larry | 21 | | 3 | Bob | 26 | | 4 | James | 22 | | 5 | Robert | 28 | | 6 | Mike | 29 | | 7 | Carol | 24 | | 8 | David | 20 | | 9 | Maxwell | 30 | +----+----------+---------+ 9 rows in set (0.00 sec)
这是按限制后的顺序查询:
mysql> select *from -> ( -> select *from OrderByAfterLimit order by UserAge DESC LIMIT 9) AS tbl1 -> order by UserName;
以下是输出:
+----+----------+---------+ | Id | UserName | UserAge | +----+----------+---------+ | 3 | Bob | 26 | | 7 | Carol | 24 | | 8 | David | 20 | | 4 | James | 22 | | 1 | John | 23 | | 2 | Larry | 21 | | 9 | Maxwell | 30 | | 6 | Mike | 29 | | 5 | Robert | 28 | +----+----------+---------+ 9 rows in set (0.00 sec)