我有表comments
的这些列:
id
content
add_date
uid
school_id
行可以具有相同的school_id。
我想根据add_date选择最新数据,但每个school_id仅 1行(school_id
不重复),限制为10。
我已经尝试了很多代码,但它对我不起作用。 任何帮助将不胜感激。
答案 0 :(得分: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
答案 1 :(得分: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
如果您想选择返回10 rows
,请添加order by
或Where
条款
答案 2 :(得分: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)
上创建索引