无法根据发布时间将最新值添加到Mysql表中

时间:2015-03-27 07:43:50

标签: mysql

SELECT * FROM discussion_comments GROUP BY disc_id ORDER BY published_date DESC

我有如下所示的表格示例:

CREATE TABLE example
(
id int(11),
cname varchar(11),
posted_date date,
posted_time varchar(20)
); 

的值如下:

INSERT INTO example
VALUES 
(1,'abc','2015-03-26','04:25 PM'),
(1,'def','2015-03-27','04:30 PM'),
(2,'ghi','2015-03-11','02:25 AM'),
(2,'jkl','2015-03-15','12:25 PM');

我试图仅根据id&和posted_date获取posted_time表中添加的最新值(1,'def','2015-03-27','04:30 PM') (2,'jkl','2015-03-15','12:25 PM') 字段。

我想要达到的结果是:

SELECT * FROM `example GROUP BY id ORDER BY posted_date DESC 

我尝试的查询如下:

{{1}}

我没有得到理想的结果。我哪里出错?

2 个答案:

答案 0 :(得分:1)

有很多方法,其中一种方式是left join

select e1.* from example e1 
left join example e2 on e1.id = e2.id 
and e1.posted_date < e2.posted_date where e2.id is null;

Uncorrelated Sub-query

select e1.* from example e1 
join ( 
   select id,max(posted_date) as posted_date from example group by id 
)x 
on x.id = e1.id and x.posted_date = e1.posted_date ; 

答案 1 :(得分:1)

如果要对desc日期+时间进行排序

select * from (select * from example order by STR_TO_DATE(CONCAT(posted_date,posted_time),'%Y-%m-%d%h:%i %p') desc) as xx group by id;

如果您想按日期排序desc

SELECT * FROM (select * from example order by posted_date desc) as ex group by id

在处理日期操作时,IMHO存储为时间戳更好,除非你有多个时间戳字段是同一个表。