MySQL Group By get title column with smallest date value

╄→гoц情女王★ 提交于 2019-12-25 02:13:38

问题


I have a query like:

SELECT *
FROM table
GROUP BY sid
ORDER BY datestart desc
LIMIT 10

which returns the last 10 sid groups.

For each of these groups, I need the title column of the row with the lowest datestart value

I tried using

SELECT *, min(datestart)

but that didn't return the row with the smallest datestart value, just the lowest datestart. I need the title from the lowest datestart.

(Relevant) Table Structure:

    CREATE TABLE `table` (
  `title` varchar(1000) NOT NULL,
  `datestart` timestamp NOT NULL default CURRENT_TIMESTAMP,
  `sid` bigint(12) unsigned NOT NULL,
  KEY `datestart` (`datestart`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Any ideas?


回答1:


Updated answer

select t1.* from `table` as t1
inner join (
select sid,min(datestart) as elder
from `table`
group by sid
order by elder desc limit 10) as t2
on t1.sid = t2.sid and t1.datestart = t2.elder

Use a composite index on (sid,datestart)




回答2:


Try this query. You will get expected results. If it don't work change Table_2.datestart > Table_1.datestart by Table_2.datestart < Table_1.datestart

SELECT title, datestart
FROM `table` AS Table_1
LEFT JOIN `table` AS Table_2 ON (Table_2.sid = Table_1.sid AND Table_2.datestart > Table_1.datestart)
Table_2.sid IS NULL;

Edited query

SELECT Table_1.title, Table_1.datestart
FROM `table` AS Table_1
LEFT JOIN `table` AS Table_2 ON (Table_2.sid = Table_1.sid AND Table_2.datestart > Table_1.datestart)
Table_2.sid IS NULL;


来源:https://stackoverflow.com/questions/5697442/mysql-group-by-get-title-column-with-smallest-date-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!