我有一张桌子,它和这张桌子相似
ID Name Age Status
1 John 32 Life
2 Andre 99 Life
3 Anton 89 Dead
4 Maria 99 Life
5 Mario 13 Life
6 Santi 89 Dead
7 Anggy 56 Dead
8 Amir 99 Life
我想做这样的事情
1.按状态分组行(生命)
2.从该组中获取最大年龄(99)(仅需要最大数量)
4.按年龄创建新组,并按ID排序。
结果将是
8 Amir 99 Life
4 Maria 99 Life
2 Andre 99 Life
是否只能对该作业使用1行查询?使用一些(php)数据处理它并不难以得到我想要的结果,但我想使代码尽可能干净,所以也许我可以在一个查询中完成这3步?
答案 0 :(得分:1)
我认为正确的逻辑是:
select t.id, t.name, t.age, t.status
from table t join
(select max(t2.age) from table t2 where t2.status = 'life') m
on t.age = m.age
where t.status = 'life'
order by id desc;
答案 1 :(得分:0)
select id, name, age, status
from thetable
where age =
(select max(age)
from thetable
where status="Life"
)
where status="Life"
order by id desc
答案 2 :(得分:0)
使用以下提到的查询:
SELECT
*
FROM
t4
CROSS JOIN
(SELECT
MAX(`age`) AS 'age'
FROM
t4
WHERE
`status` = 'Life') AS t5
WHERE
`status` = 'Life' AND t4.`age` = t5.age
ORDER BY `id` DESC;