如何从NID
开始每隔7天选择一个最新的UID
,从今天开始算起。
如果今天是7月11日,则下表
+-----+------------+-----+
| NID | timestamp | UID |
+-----+------------+-----+
| 1 | 1341719851 | 8 | //July 7
| 2 | 1341115051 | 8 | //July 1
| 3 | 1341547051 | 8 | //July 6
| 4 | 1341719851 | 8 | //July 8
| 5 | 1341979051 | 8 | //July 11
| 6 | 1341806251 | 9 | //July 9
| 7 | 1341460651 | 9 | //July 5
| 8 | 1341892651 | 9 | //July 10
+-----+------------+-----+
将输出:
+-----+------------+-----+
| NID | timestamp | UID |
+-----+------------+-----+
| 2 | 1341115051 | 8 | //July 1
| 5 | 1341979051 | 8 | //July 11
| 8 | 1341892651 | 9 | //July 10
+-----+------------+-----+
在过去7天内,每位用户的最新NID
为'5'
和'8'
,在之前的7天内,最近的NID
为'2'
等等...
我假设,Group By会做的伎俩;但我不知道从哪里开始。
更新
根据最佳答案,这是有效的查询:
SELECT nid, timestamp, uid, weeks_ago
FROM (
SELECT nid, timestamp, uid, FLOOR(
(UNIX_TIMESTAMP()- timestamp)/604800
) weeks_ago
FROM `table`
ORDER BY timestamp DESC
) x
GROUP BY uid, weeks_ago
答案 0 :(得分:3)
select nid, max(timestamp), uid, weeks_ago
from (select nid, timestamp, uid, floor(datediff(now(), from_unixtime(timestamp))/7) weeks_ago
from mytable) x
group by nid, uid, weeks_ago
答案 1 :(得分:0)
select * from (
(
select nid, uid,timestamp,floor(datediff(now(), from_unixtime(timestamp))/7) as weeks,from_unixtime(timestamp) as Dt from test t1 order by dt desc limit 0,2)
Union
(
select nid, uid,timestamp,
floor(datediff(now(), from_unixtime(timestamp))/7) as weeks,from_unixtime(timestamp) as Dt
from test t2 group by weeks having weeks>0 order by dt asc limit 0,1
)
) t4
可能会解决您的问题。试试这个