我的表是这样的
字段
id,title,com_id,updatetime
id 主键自增
title varchar 20
com_id int 这个就是公司ID,外键
updatetime int 更新日期。用的是int
我 要的是 最新的3条公司新闻,就是说3条记录。而且是3个公司的新闻。最先是按updatetime排的。
比如我有记录
1 aaa 1 1
2 bbb 1 2
3 ccc 2 3
4 eee 2 5
5 fff 4 8
6 ggg 1 9
7 iii 2 10
8 kkk 1 12
那最后的记录结果我想要的结果是
最新的日期是 12,10,9,8 第6条因为1公司已经出现过了所以去掉了
最后的结果是
8 kkk 1 12
7 iii 2 10
5 fff 4 8
这个语句怎么写呢???数据库是mysql 的
[b]问题补充:[/b]
这么无法保障 日期是否重复。有可能重复的 。
还有ID是自增长的。日期的话是乱的。比如第一条记录有可能日期会被更新,那马上就是最新的记录了 。
给两个版本,如果更新时间列确保是不重复的,则
[code="sql"]
select * from table3
where updatetime in(
select max(updatetime) as maxrow
from table3
group by com_id);
[/code]
否则假定id大的记录更新,则代码有些丑陋,
[code="sql"]
select *
from table3
where id in(
select max(id)
from table3
where updatetime in(
select max(updatetime) as maxrow
from table3
group by com_id)
group by updatetime);
[/code]
以上均在mysql5下测试通过
后面加上limit 3,取前三条。
如果日期无法唯一,就用第二条丑陋点的sql吧