dimanche 5 avril 2020

Mysql left join store previous value if condition query correction

When I perform left join from a derived table (a mapping table) using a variable @prevValue in if condition to store previous value, I get different results

Here are the tables

Table_1

Date                    Value
2020-03-02 00:00:00      0
2020-03-02 07:00:00      1
2020-03-02 12:00:00      0

Table_2
2020-03-02 00:00:00      0
2020-03-02 07:00:00      1
2020-03-02 12:00:00      1
2020-03-02 14:00:00      0

Mapping_table
Date
2020-03-02 00:00:00
2020-03-02 01:00:00
2020-03-02 02:00:00
2020-03-02 03:00:00
...

Here is my query (I even added counters to check how mysql joins the table)

SET @prevValue=0;

SELECT DATE_FORMAT(P.date,'%Y-%m-%d %H:%i:%s') AS `date`, 
IF(D.date IS NULL ,@prevValue, @prevValue:=D.value) AS `dataValue`
    FROM (SELECT `T`.`date` FROM `Mapping_table` AS `T`
     WHERE (date >= '2020-03-02 00:00:00') AND (date <= '2020-03-02 23:59:00')) AS `P`
LEFT JOIN `Table_1` AS `D` ON D.date=P.date ORDER BY `P`.`date` ASC;

Results to the following:

Date                    Val
---------------------------
"2020-03-02 00:00:00"   "0"
"2020-03-02 00:01:00"   \N
"2020-03-02 00:02:00"   \N
"2020-03-02 00:03:00"   \N
"2020-03-02 00:04:00"   \N
"2020-03-02 00:05:00"   \N

Querying to Table_2 (I just replaced the query with Table_2) yields the following:

Date                    Val
---------------------------
"2020-03-02 00:00:00"   "0"
"2020-03-02 00:01:00"   "0"
"2020-03-02 00:02:00"   "0"
"2020-03-02 00:03:00"   "0"
"2020-03-02 00:04:00"   "0"
"2020-03-02 00:05:00"   "0"

My desired result with be the last one. I expect the left join from Table_1 should return the same as Table_2 result? Do you guys have an idea what should I change in my query or explain why this happens?

Mysql version used 5.7

Aucun commentaire:

Enregistrer un commentaire