我有一个类似的查询:
SELECT *
FROM table
GROUP BY sid
ORDER BY datestart desc
LIMIT 10
返回最后10个sid组。
对于这些组中的每一组,我需要具有最低日期开始值
的行的标题列我尝试使用
SELECT *, min(datestart)
但是没有返回具有最小datestart值的行,只返回最低的datestart。我需要从最低日期开始的标题。
(相关)表格结构:
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;
有什么想法吗?
答案 0 :(得分:0)
尝试此查询。您将获得预期的结果。如果不起作用,则按Table_2.datestart > Table_1.datestart
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;
已编辑的查询
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;
答案 1 :(得分:0)
更新回答
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
在(sid,datestart)上使用复合索引