2013-11-09 45 views
1

數據庫中的數據:加入行之前最近的日期排

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的解決方案,但不知道會有多好。有些想法我已經考慮:

  1. 某種連接在同一個表 - 不知道怎麼雖然
  2. 子查詢的選擇 -

    select date as cur_date , (select max(date) from table where date < cur_date group by account) as prev_date... - 這似乎是它可以是令人難以置信的密集

  3. 會話變量 - 在每行上設置一個會話變量,它將成爲下一行的先前數據,例如

    select date as cur_date , @prev_date as prev_date , @prev_date:=date...

有沒有人有這樣的問題的經驗,是有沒有好的解決辦法?我有任何可能導致未來問題的想法是否有積極的消極影響?

回答

1

我會使用SQL和應用程序代碼的組合。由於我不是一名PHP程序員,因此我只會描述用於應用程序部分的邏輯。

首先查詢。

select account, date, random_data 
from thetable 
where date >= YourDateVariable 

union 

select account, date, random_data 
from thetable join 
(select account acc, max(date) maxdate 
from thetable 
where date <= YourDateVariable 
group by account) x on account = acc and date = max(date) 
where date <= YourDateVariable 

order by account, date 

對於應用程序的代碼,這樣做:

Set a variable called ThisAccount to 0. 
Set a row counter variable to 0. 
Create an empty 2D array 
Start looping through your query results 
Put the account value and random data into the first two columns 
    of the next available row of the array 
Compare the account value to the value of the ThisAccount variable. 
    If they are the same, get the previous date and random data from 
    the previous row in the array. 
Set the ThisAccount variable to the current account value. 
Increment your row counter variable 
End of loop.