如何从表中选择所有内容,如果列name
的值相同,则只选择具有最大id
值的行,以便如果有这样的表:< / p>
id name age country
---+------+---+-------
1 bob 24 UK
2 john 48 USA
3 janet 72 USSR
4 bob 96 Ukraine
它只会选择id为最高的'bob',结果会返回:
id name age country
---+------+---+-------
2 john 48 USA
3 janet 72 USSR
4 bob 96 Ukraine
谢谢。
答案 0 :(得分:7)
尝试此查询
select * from table_name where ID in(select MAX(ID) from table_name group by name)
答案 1 :(得分:3)
您可以使用not exists
子查询来过滤掉具有相同名称和更高ID的行:
select *
from People p1
where not exists
(
select *
from People p2
where p1.Name = p2.Name
and p2.Id > p1.Id
)
答案 2 :(得分:2)
您可以使用子查询计算每个名称的最大ID,然后返回与子查询返回的ID匹配的所有行:
SELECT *
FROM People
WHERE id IN (SELECT MAX(id) FROM People GROUP BY Name)
请参阅小提琴here。
答案 3 :(得分:2)
你可以这样做:
Select Table_1.* from table_1 inner join (
Select Max(ID) as ID from Table_1 Group by ID) x On Table.Id on x.ID