我对sql有点新,对于我的项目,我需要做一些数据库排序和过滤:
假设我的数据库如下所示:
==========================================
| id | email | name
==========================================
| 1 | 123@test.com | John
| 2 | 234@test.com | Peter
| 3 | 234@test.com | Steward
| 4 | 123@test.com | Ethan
| 5 | 542@test.com | Bob
| 6 | 123@test.com | Patrick
==========================================
我应该怎样做只返回带有相同电子邮件的最后一列:
==========================================
| id | email | name
==========================================
| 3 | 234@test.com | Steward
| 5 | 542@test.com | Bob
| 6 | 123@test.com | Patrick
==========================================
提前致谢!
答案 0 :(得分:2)
SQL查询:
SELECT * FROM test.test1 WHERE id IN (
SELECT MAX(id) FROM test.test1 GROUP BY email
);
希望这能解决您的问题。感谢。
答案 1 :(得分:1)
在SQL中执行此操作的一般方法是使用ANSI标准row_number()
函数:
select t.*
from (select t.*, row_number() over (partition by email order by id desc) as seqnum
from t
) t
where seqnum = 1;
答案 2 :(得分:1)
您可以使用以下查询来获取MAX
的{{1}} id
值:
email
使用上述查询作为派生表,您可以获得整个记录:
SELECT email, MAX(id)
FROM mytable
GROUP BY email
答案 3 :(得分:0)
这是一个更清晰的方法:
SELECT *<br>
FROM table<br>
ORDER BY email DESC<br>
LIMIT 1;