Search code examples
mysqlmysql-logic

WHERE clause causing table to omit LEFT JOIN rule


I am essentially attempting to modify this stored procedure.

Modified stored procedure:

CREATE PROCEDURE sp1(d1 date, d2 date, client INT(10))
    declare d datetime;

    create TEMPORARY TABLE foo (d date NOT NULL, Amount INT(10) DEFAULT 0);

    set d = d1;

    while d <= d2 do 
        insert into foo (d) values (d);
        set d = date_add(d, interval 1 day);
    end while;

    SELECT SUM(p.Amount), foo.d
    FROM foo LEFT JOIN ItemTracker_dbo.Payment ON foo.d = p.Datetime
    WHERE p.ClientId = ClientId
    GROUP BY
        foo.d;

    DROP TEMPORARY TABLE foo;
end PROCEDURE

NOTE: the WHERE clause... p.ClientId = client

I was wracking my brain trying to figure out why it was omitting the zero's.

upon removal of WHERE p.ClientId = client the procedure began to return NULL...

Why is the WHERE clause ommiting the null rows? I am probably misunderstanding what exactly a LEFT JOIN is.

How can I go about filtering the SUM(p.Amount) results to only return the sum WHERE clientId = client?


Solution

  • It should work if you put all the conditions into the LEFT JOIN condition:

    SELECT SUM(p.Amount), foo.d
    FROM foo
    LEFT JOIN ItemTracker_dbo.Payment p ON foo.d = p.Datetime AND p.ClientId = ClientId
    GROUP BY
        foo.d;