我有这张桌子:
name | age
John | 35
Amanda | 34
Jane | 34
Jack | 34
Craig | 32
Jason | 32
Phil | 32
Kris | 32
Tyler | 25
Harry | 25
Duke | 24
我想按年龄desc订购并选择前五行。但如果有更多的人与第5行的年龄相同,我也希望他们在我的结果中。类似于:(SELECT * FROM people ORDER BY age DESC LIMIT 0, 5 as W) UNION (SELECT * FROM people WHERE age = W[4].age
)
所以上面例子的结果是:
John | 35
Amanda | 34
Jane | 34
Jack | 34
Craig | 32
Jason | 32
Phil | 32
Kris | 32
有什么方法可以做到吗?非常感谢你
答案 0 :(得分:1)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(name VARCHAR(12) NOT NULL PRIMARY KEY
,age INT NOT NULL)
;
INSERT INTO my_table VALUES
('John' ,35),
('Amanda' ,34),
('Jane' ,34),
('Jack' ,34),
('Craig' ,32),
('Jason' ,32),
('Phil' ,32),
('Kris' ,32),
('Tyler' ,25),
('Harry' ,25),
('Duke' ,24);
SELECT DISTINCT y.*
FROM
( SELECT *
FROM my_table
ORDER
BY age DESC
LIMIT 5
) x
JOIN my_table y
ON y.age = x.age;
+--------+-----+
| name | age |
+--------+-----+
| John | 35 |
| Amanda | 34 |
| Jane | 34 |
| Jack | 34 |
| Craig | 32 |
| Jason | 32 |
| Phil | 32 |
| Kris | 32 |
+--------+-----+
<强> SQL DEMO 强>
答案 1 :(得分:0)
你必须使用内部查询来选择前5个年龄,然后反转顺序以选择最后一个。
使用Limit 4, 1
跳过前4并选择最后一个
<强> SQL DEMO 强>
SELECT *
FROM (SELECT *
FROM people
ORDER BY age DESC
LIMIT 5 ) as w
UNION
SELECT *
FROM people
WHERE age = (SELECT age
FROM Table1
ORDER BY `age` DESC
LIMIT 4, 1)
<强>输出强>
答案 2 :(得分:0)
如果您尝试
,该怎么办?SELECT * FROM people
WHERE Age IN (SELECT DISTINCT Age FROM people ORDER BY Age DESC LIMIT 5)