數據庫中的數據:加入行之前最近的日期排
id | account | date | random_data
1 | 1 | 01/01/2013 | qw
2 | 2 | 05/01/2013 | er
3 | 2 | 09/01/2013 | ty
4 | 1 | 05/01/2013 | ui
5 | 2 | 11/01/2013 | op
6 | 1 | 12/01/2013 | as
嗨,讓我們說,我想記錄從2013/05/01開始 - 注意prev_date的第一行仍然顯示較早的日期比05/01意味着整個表格仍然需要被搜索。
結果數據:
account | cur_date | random_data | prev_date | prev_rand_data
1 | 05/01/2013 | ui | 01/01/2013 | qw
1 | 12/01/2013 | as | 05/01/2013 | ui
2 | 05/01/2013 | er | null | null
2 | 09/01/2013 | ty | 05/01/2013 | er
2 | 11/01/2013 | op | 09/01/2013 | ty
所以我不知道什麼是最好的,最優化的查詢我可以用這一點。我不反對php的解決方案,但不知道會有多好。有些想法我已經考慮:
- 某種連接在同一個表 - 不知道怎麼雖然
子查詢的選擇 -
select date as cur_date , (select max(date) from table where date < cur_date group by account) as prev_date...
- 這似乎是它可以是令人難以置信的密集會話變量 - 在每行上設置一個會話變量,它將成爲下一行的先前數據,例如
select date as cur_date , @prev_date as prev_date , @prev_date:=date...
有沒有人有這樣的問題的經驗,是有沒有好的解決辦法?我有任何可能導致未來問題的想法是否有積極的消極影響?