0

I have a MySQL table with 1000 rows. And I want to get 4 specific rows based on linear function as step (get value of row, last position must be the last row, row number 1000). Example:

---------------------
 id  | value
---------------------
  1  | 3
  2  | 1
  3  | 5
  4  | 4
 ... | ...
 997 | 2
 998 | 0
 999 | 7
1000 | 4
--------------------

Step as linear function (1,2,3....,N)

*) step=1  =>  i will get 4 rows of id : 997,998,999,1000   
       first row to get is row number 997, last row is row number 1000
       result = 2,0,7,4
*) step=2  =>  i will get 4 rows of id : 994,996,998,1000
*) step=3  =>  i will get 4 rows of id : 991,994,997,1000
*) step=4  =>  i will get 4 rows of id : 988,992,996,1000
*) step=5  =>  i will get 4 rows of id : 985,990,995,1000
.....
*) step=330 => i will get 4 rows of id : 10,340,670,1000
*) step=331 => i will get 4 rows of id : 7,338,669,1000
*) step=332 => i will get 4 rows of id : 4,336,668,1000
*) step=333 => i will get 4 rows of id : 1,334,667,1000

How to do it in PHP?

4

1 回答 1

1

考虑到您希望最后一行始终为 id 1000:

function linear($step) {

 $query = "SELECT * FROM TABLE WHERE id IN (1000, 1000 - $step, 1000 - $step * 2, 1000 - $step * 3)"
 $result = mysql_query($query)
}

如果您不知道最后一个 ID 是什么:

function linear($step) {
 $lastId = mysql_fetch_assoc(mysql_query("SELECT id FROM TABLE ORDER BY id DESC LIMIT 1"))['id']
 $query = "SELECT * FROM TABLE WHERE id IN ($lastId, $lastId - $step, $lastId - $step * 2, $lastId - $step * 3)"
 $result = mysql_query($query)
}

随时询问您是否需要更多信息。不客气。

于 2013-09-19T16:55:22.753 回答