MySQL Group By 获取具有最小日期值的标题列
我有一个像这样的查询:
SELECT *
FROM table
GROUP BY sid
ORDER BY datestart desc
LIMIT 10
它返回最后 10 个 sid 组。
对于每个组,我需要
尝试使用的
SELECT *, min(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;
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新的答案
在(sid,datestart)上使用复合索引
Updated answer
Use a composite index on (sid,datestart)
尝试这个查询。您将得到预期的结果。如果它不起作用,请更改
Table_2.datestart > Table_1.datestart
byTable_2.datestart < Table_1.datestart
已编辑的查询
Try this query. You will get expected results. If it don't work change
Table_2.datestart > Table_1.datestart
byTable_2.datestart < Table_1.datestart
Edited query