0

我有这些表的列comments

id
content
add_date
uid
school_id

行可以具有相同的 school_id。

我想根据add_date选择最新的数据,但每个school_id只有1行(不重复school_id),限制为10。

我已经尝试了很多代码,但它对我不起作用。任何帮助,将不胜感激。

4

3 回答 3

1

这就是我们所说Greatest N per Group的。您可以通过放入子查询来实现这一点,这样它就可以与非分组表 ( comments) 连接起来。尝试这个:

SELECT  c.*
FROM
        (
            SELECT school_id, MAX(add_date) maxDate
            FROM comments
            GROUP BY school_id
        ) x INNER JOIN comments c
            ON  x.school_id = c.school_ID AND
                x.maxDate = c.add_date
ORDER BY x.maxDate desc
LIMIT 10
于 2012-08-03T00:54:39.117 回答
0
select c1.*
  from comments c1
 where add_date = (select max(add_date) from comments c2 where c2.school_id =c1.school_id)
 order by add_date desc
 limit 10

在评论(add_date)和评论(school_id,add_date)上创建索引

于 2012-08-03T00:57:32.427 回答
0
select C.ID, C.Content, t1.MaxDate as [add_date], C.uid, t1.school_id
from (selet school_id, max(add_Date) as 'MaxDate'
from comments
group by school_id) T1
inner join comments C on T1.school_id = C.school_id and C.add_Date= T1.MaxDate
LIMIT 10

如果要选择rows返回哪 10 个,添加一个order by, 或一个Where子句

于 2012-08-03T00:53:00.153 回答