MySQL - 限制连接中的行数?

时间:2010-02-03 02:32:01

标签: sql mysql

不确定在这里找一些指导......

我有以下表格:

site_text
id   site_id    text    date_added
1    1          ...     2010-02-02 10:01:00
2    1          ...     2010-02-02 10:01:20
3    2          ...     2010-02-02 10:01:00
4    1          ...     2010-02-02 10:01:40
5    2          ...     2010-02-02 10:02:00

sites
id   site_name
1    www.a.com
2    www.b.com
....

我正在尝试在site_text中为每个站点选择最后2行(按日期desc排序)。你能用一个查询做到这一点吗?有类似的东西,但每个网站只找到2行吗?

SELECT * 
  FROM site_text st 
  JOIN sites s ON st.site_id = s.id 
 WHERE st.date_added > '2010-02-01 23:32:04' 
ORDER BY s.id, st.date_added DESC

编辑:最后,我会寻找第4,2,5,3行。

1 个答案:

答案 0 :(得分:2)

这里有一个聪明的解决方案,CTE和RANK() OVER DATE_ADDED在Pg 8.4中,但因为你使用的是mysql,我唯一能想到的就是一个计算复杂的查询:< / p>

-- Select the top date for each site_id
SELECT DISTINCT id FROM site_text
    GROUP BY site_id, date_added
    ORDER BY site_id, date_added
UNION
-- Select the top date for each site_id
SELECT DISTINCT id FROM site_text
    GROUP BY site_id, date_added
        -- Excluding the top date.
    WHERE id NOT IN (
        SELECT DISTINCT id FROM site_text
        GROUP BY site_id, date_added
        ORDER BY site_id, date_added
    )
    ORDER BY site_id, date_added
;

故事的道德,使用Pg。可能有更多特定于mysql的方法来生成更可接受的性能配置文件。