【发布时间】:2014-10-21 17:59:08
【问题描述】:
我需要为一个特定用户选择表中的最新三个条目,并为另一列选择唯一值。这是我的数据库的结构:
time_tracking
id
user
todo
tracked_time
start_date
start_time
running
所以todo 列必须是唯一的,我需要每个user 按start_date 和start_time 降序排列的三个最新的。
我尝试使用DISTINCT 和 Google 周围的许多其他答案,但似乎没有任何帮助。
使用类似的东西
SELECT * FROM time_tracking WHERE user = 4735350 GROUP BY todo ORDER BY start_date DESC, start_time DESC LIMIT 3
几乎得到它,但如果它在以前的值中,它会跳过一些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。
【问题讨论】:
-
更改 select * 以选择不同的字段。
-
您需要数据中的哪些列?仅当您只需要不同的列时, distinct 才有效。
-
我需要@MarshallTigerus 和@DanBracuk 表中的所有列,所以我不能使用
DISTINCT。 -
我不明白... todo 必须是唯一的吗?因为一开始你说是,但后来你说任何 todo 都会被跳过……你想要一个独特的 user-todo 组合吗?
-
todo必须是唯一的。我最后说的是,使用我发布的代码,一些应该出现的待办事项正在被跳过@carexcer。
标签: mysql sql database distinct sql-order-by