jeudi 2 avril 2020

Mysql left join derived table inconsistent result

When I perform left join from a derived table (a mapping table), 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;
SET @testCtr:=0;

SELECT DATE_FORMAT(P.date,'%Y-%m-%d %H:%i:%s') AS `date`, 
@prevValue,
D.value AS 'valueOriginal',
@testCtr AS 't1',
IF(D.date IS NULL ,@prevValue, @prevValue:=D.value) AS `dataValue` ,
@prevValue,
D.value AS 'valueOriginal',
(@testCtr:=@testCtr+1) AS 't2'
    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:

"2020-03-02 00:00:00"   "0" "0" "0" "0" "0" "0" "1"
"2020-03-02 00:01:00"   \N  \N  "3" \N  \N  \N  "4"
"2020-03-02 00:02:00"   \N  \N  "4" \N  \N  \N  "5"
"2020-03-02 00:03:00"   \N  \N  "5" \N  \N  \N  "6"
"2020-03-02 00:04:00"   \N  \N  "6" \N  \N  \N  "7"

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

"2020-03-02 00:00:00"   "0" "0" "0" "0" "0" "0" "1"
"2020-03-02 00:01:00"   "0" \N  "1" "0" "0" \N  "2"
"2020-03-02 00:02:00"   "0" \N  "2" "0" "0" \N  "3"
"2020-03-02 00:03:00"   "0" \N  "3" "0" "0" \N  "4"
"2020-03-02 00:04:00"   "0" \N  "4" "0" "0" \N  "5"

I expect the left join from Table_1 should return the same as Table_2 result? I also don't understand why the counters are not same value? Is it because the two tables have different size?

Mysql version used 5.7

Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire