user2758001
user2758001

Reputation: 119

How to get linear function row in MySQL?

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?

Upvotes: 0

Views: 140

Answers (1)

alandarev
alandarev

Reputation: 8635

Considering you want last row to always be 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)
}

In case you do not know what is the last 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)
}

Feel free to ask if you need more information. You are welcome.

Upvotes: 1

Related Questions