I have the following table:
id speed date 1 0 01/01/2015 2 0 01/01/2015 3 0 01/01/2015 4 0 01/01/2015 5 0 01/01/2015 6 0 01/01/2015 7 25 01/01/2015 8 78 01/01/2015 9 13 01/01/2015 10 45 01/01/2015 11 0 01/01/2015 12 80 01/01/2015 13 86 01/01/2015 14 10 01/01/2015 15 0 01/01/2015 16 0 01/01/2015 17 0 01/01/2015 18 0 01/01/2015
This is just a small part of the table, it has many dates. Each new date starts and ends with an unknown amount of zeros. And I have to skip these zeros and get only what's between them. So I came up with the following solution:
Get the ID of the first row whose speed is positive (in our table it's id number 4).
Get the ID of the last row whose speed is positive (in our table it's id number 12).
Get lines between these two IDs (4 and 12).
I get the id
of the first row whose speed
is positive:
$q1=$conn->prepare("SELECT * FROM tableX WHERE speed > 0 order by date asc LIMIT 1");
$q1->execute();
$r1=$q1->fetch();
$first_id = $r1['id'];
And then get the id
of the last row whose speed
is positive:
$q2=$conn->prepare("SELECT * FROM tableX WHERE speed > 0 order by date desc LIMIT 1");
$q2->execute();
$r2=$q2->fetch();
$last_id = $r2['id'];
And then use those id
s to get what I want:
$q3=$conn->prepare("SELECT * FROM tableX WHERE id between '$first_id' and '$last_id'");
$q3->execute();
while($r3=$q3->fetch(){}
Expected result:
id speed date 7 25 01/01/2015 8 78 01/01/2015 9 13 01/01/2015 10 45 01/01/2015 11 0 01/01/2015 12 80 01/01/2015 13 86 01/01/2015 14 10 01/01/2015
My code is actually working but I think this solution of mine is lame, so I am looking for an improvement, kind of all these three queries in one!
date asc
it is kind of random which row withspeed > 0
you'll get. In the data given, all rows have the same date, and it depends on the database implementation which row id you'll get first or last. As such this code is broken, or dependent on your choice of database engine and their choice of returning rows when the order column is identical \$\endgroup\$$r3
line also doesn't make sense. \$\endgroup\$