我需要在一个表中为一个特定用户选择最新的三个条目,并使用另一个列的唯一值。这是我的数据库的结构:
time_tracking
id
user
todo
tracked_time
start_date
start_time
running
因此todo
列必须是唯一的,并且我需要按user
和start_date
降序排序的每个start_time
最近的三个。
我试图在Google周围使用DISTINCT
和许多其他答案,但似乎都没有帮助
使用像
SELECT * FROM time_tracking WHERE user = 4735350 GROUP BY todo ORDER BY start_date DESC, start_time DESC LIMIT 3
ALMOST 获取它,但如果它是以前的值,它会跳过一些todos
,如下所示:
id |user |todo |start_date |start_time
1 |4735350 |1 |2014-09-10 |10:00:00
2 |4735350 |2 |2014-09-11 |10:00:00
3 |4735350 |1 |2014-09-11 |11:00:00 -- gets skipped because of id=1 even though it has a more recent date
编辑:我需要表格中的所有列,因此我似乎无法使用DISTINCT
。
答案 0 :(得分:0)
您可以通过操作获得最大的start_date值,并可以使用EXISTS
SELECT * FROM
time_tracking t
WHERE user = 4735350
AND exists
(
SELECT 1
FROM time_tracking
WHERE user = 4735350
GROUP BY todo
HAVING MAX(start_date) = t.start_date
and MAX(start_time) = t.start_time
)
order by start_date desc, start_time desc
LIMIT 3
答案 1 :(得分:0)
你可以试试这个。
SELECT * FROM time_tracking WHERE user = 4735350 GROUP BY 1 ORDER BY start_date DESC, start_time DESC LIMIT 3
将group by
从待办事项更改为1
编辑: 好吧,我正在尝试一个新的解决方案,但我得去,但至少,尝试这样的事情:
select t1.*
from (select todo, MAX(start_date) start_date
from time_tracking group by todo
) t2 join time_tracking t1 on t1.todo = t2.todo and t1.start_date = t2.start_date
order by start_date desc, start_time desc
LIMIT 3;
问候。
答案 2 :(得分:0)
SELECT [user],todo, max(start_time),max(start_date) FROM time_tracking WHERE [user] = 4735350 GROUP BY [user],todo
尝试此查询...工作