如果您正在使用具有元组功能的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 |
您可以通过使用上述关系型数据库的元组可用 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中不起作用。很少有数据库不支持元组-capable的IN
,不幸的是Sql Server就是其中之一。