I want to return the row number of a particular row (so how many rows before a given row).
Now the problem is the PRIMARY_KEYs are not sequential, so there are 'gaps' inside them, because sometimes I have to DELETE rows.
id = 1
id = 2
id = 5
id = 9
id = 10
So the only option to get the row number is to use a COUNT(*):
SELECT COUNT(*) FROM table WHERE id < selected_row_id;
But for a given page I have to perform this operation multiple times.. so one solution is to use a foreach loop, like:
foreach($foo as $item){
mysql_query("SELECT COUNT(*) FROM table WHERE id < $item['id']");
//...
}
But I think it's not optimal...if one have thousands of rows and 80-100 iterations for the above foreach.
Another solution would be to rebuild the entire id
column after DELETING a row.. but because foreign constraints / references I think this isn't a good step, too.
So if COUNT(*) in a foreach
is not viable, then is there anyone who faced this type of problem, what would be the optimal solution?
Thanks for your time, and sry for my bad english.