我想检索具有最近修改时间的所有记录。 例如,拿这个表:
|page_url|last_modified|
---------
|abc.com |2010-10-01 10:00:00|
|xyz.com |2010-10-04 12:10:00|
|xyz.com |2010-10-04 12:00:00|
|xyz.com |2010-10-04 10:00:00|
|abc.com |2010-10-01 08:00:00|
输出应包含以下数据:
|page_url|last_modified|
---------
|abc.com |2010-10-01 10:00:00|
|xyz.com |2010-10-04 12:10:00|
我尝试使用下面的子句但不适合我:(
SELECT page_url, last_modified
FROM
my_table
HAVING MAX(last_modified);
编辑1:我的表中有25个字段可供使用。但是,我想我不能为所有人申请分组。现在该怎么办?
答案 0 :(得分:4)
无需在此HAVING
子句中使用GROUP BY
。
SELECT page_url, MAX(last_modified)
FROM my_table
GROUP BY page_url
更新1
SELECT a.*
FROM my_table a
INNER JOIN
(
SELECT page_url, MAX(last_modified) recentDate
FROM my_table
GROUP BY page_url
) b ON a.page_url = b.page_url AND
a.last_modified = b.recentDate
答案 1 :(得分:2)
尝试在group by
声明
max()
和select
SELECT page_url, max(last_modified)
FROM my_table
group by page_url
更多信息:
答案 2 :(得分:2)
如果您使用的是具有元组功能IN
的RDBMS,如Postgresql,MySql和Oracle。您可以使用以下方法。
所以,让我们说你已经有了这样的现有观点:
create view page_latest as
SELECT page_url, MAX(last_modified) recentDate
FROM tbl
GROUP BY page_url;
select * from page_latest;
...输出
| PAGE_URL | RECENTDATE |
---------------------------------------------
| abc.com | October, 01 2010 10:00:00+0000 |
| xyz.com | October, 04 2010 12:10:00+0000 |
......基于这些数据:
| PAGE_URL | LAST_MODIFIED | MESSAGE |
------------------------------------------------------------------
| abc.com | October, 01 2010 10:00:00+0000 | no alarm |
| xyz.com | October, 04 2010 12:10:00+0000 | no surprises |
| xyz.com | October, 04 2010 12:00:00+0000 | fake plastic trees |
| xyz.com | October, 04 2010 10:00:00+0000 | creep |
| abc.com | October, 01 2010 08:00:00+0000 | thom yorke |
您可以通过重复使用具有上述RDBMS的元组IN的上述视图来查找所有最新消息:http://www.sqlfiddle.com/#!2/b8193/2
select *
from tbl
where (page_url,last_modified) in (select page_url, recentDate from page_latest);
输出:
| PAGE_URL | LAST_MODIFIED | MESSAGE |
------------------------------------------------------------
| abc.com | October, 01 2010 10:00:00+0000 | no alarm |
| xyz.com | October, 04 2010 12:10:00+0000 | no surprises |
不仅查询更短,而且更容易阅读。虽然如果你没有周围的视图,你可以内联一个视图"在您的查询中:http://www.sqlfiddle.com/#!2/b8193/5
select *
from tbl
where (page_url,last_modified) in
(SELECT page_url, MAX(last_modified) recentDate
FROM tbl
GROUP BY page_url);
这个答案在Sql Server中不起作用。只有少数数据库不支持具有元组功能的IN
,不幸的是Sql Server就是其中之一
答案 3 :(得分:0)
SELECT z.page_url,z.last_modified
FROM (SELECT page_url, MAX(last_modified)
FROM my_table
GROUP BY page_url) as z
ORDER BY z.page_url
答案 4 :(得分:0)
这些 -
怎么样? SELECT page_url,last_modified,other field
FROM my_table
ORDER BY page_url,last_modified
OR
SELECT distinct page_url,last_modified,other field
FROM my_table
ORDER BY page_url,last_modified