I have the following mysql table
+---------------------+------+
| time | val |
+---------------------+------+
| 2005-02-03 00:00:00 | 2.11 |
| 2005-02-04 00:00:00 | 2.11 |
| 2005-02-05 00:00:00 | NULL |
| 2005-02-06 00:00:00 | NULL |
| 2005-02-07 00:00:00 | 3.43 |
| 2005-02-08 00:00:00 | NULL |
| 2005-02-09 00:00:00 | NULL |
| 2005-02-10 00:00:00 | 5.66 |
| 2005-02-11 00:00:00 | 5.66 |
| 2005-02-12 00:00:00 | NULL |
+---------------------+------+
I want to create an algorithm (in PHP) that fill the NULL values based on the last non-null value. So the table will become the following
+---------------------+------+
| time | val |
+---------------------+------+
| 2005-02-03 00:00:00 | 2.11 |
| 2005-02-04 00:00:00 | 2.11 |
| 2005-02-05 00:00:00 |>2.11 |
| 2005-02-06 00:00:00 |>2.11 |
| 2005-02-07 00:00:00 | 3.43 |
| 2005-02-08 00:00:00 |>3.43 |
| 2005-02-09 00:00:00 |>3.43 |
| 2005-02-10 00:00:00 | 5.66 |
| 2005-02-11 00:00:00 | 5.66 |
| 2005-02-12 00:00:00 |>5.66 |
+---------------------+------+
I'm looking for clues on how to approach this situation. I'm using PHP-Laravel.
There is an SQLFiddle here for 'standard' SQL.
As comments indicate, you should be fixing this when you populate the table. That said, it can be done in PHP or MySQL. Here is one option:
Bear in mind that your result will change depending on ordering and
WHERE
and so on. UseSET @x:=0;
to define your default value for cases when first row hasNULL
value.If you need to fix the data permanently, rather than for single query, you can update the table with 'correct' values:
If you want to use just SQL, you could use this UPDATE query:
Please see a fiddle here.
The subquery will return, for every NULL row the previous date with a non-NULL value. Then I'm joining the table with itself to get the value and to update the null row.