MySQL在没有数据的情况下继续加入填充值

时间:2014-03-25 12:43:19

标签: mysql

尝试设置存储过程以与多系列图表一起使用,并且需要为每个客户填写所提交范围中的每个日期的日期值(变量传入IN),即使该客户没有交易数据也是如此特别的日期。

我有这样的查询:

select 
Customer.Name
, sum(if(Transaction.StopTime > Transaction.StartTime, Transaction.StopTime - Transaction.StartTime,0)) as TimeSpent
, Transaction.Date

from Customer

left outer join Transaction ON Transaction.CustomerID = Customer.CustomerID 
    and Transaction.Date >= str_to_date(DateFrom,'%m/%d/%Y')
    and Transaction.Date <= str_to_date(DateTo,'%m/%d/%Y')

group by Customer.Name, Transaction.Date

返回类似这样的内容:

Name | TimeSpent | Date  
------------------------------
john | 6          | 2014-03-01 
mary | 12         | 2014-03-01 
john | 0          | NULL  
mary | 12         | 2014-03-02 
john | 4          | 2014-03-03 
mary | 0          | NULL

有没有办法通过子查询获取所有行的日期,或者循环传递的变量值?

像这样:

Name | TimeSpent | Date  
------------------------------
john | 6          | 2014-03-01 
mary | 12         | 2014-03-01 
john | 0          | 2014-03-02  
mary | 12         | 2014-03-02 
john | 4          | 2014-03-03 
mary | 0          | 2014-03-03

1 个答案:

答案 0 :(得分:0)

您可以使用cross join来获取范围内的所有可能日期。然后,您可以将此字段用于left joinselect

select c.Name,
       sum(if(t.StopTime > t.StartTime, t.StopTime - t.StartTime,0)) as TimeSpent,
       td.Date
from Customer c cross join
     (select distinct t.date
      from Transaction t 
      where t.Date >= str_to_date(DateFrom, '%m/%d/%Y') and
            t.Date <= str_to_date(DateTo, '%m/%d/%Y')
     ) td left outer join
     Transaction t
     ON t.CustomerID = c.CustomerID and
        t.date = td.date
group by c.Name, td.Date;

另一方面,你应养成为DateFrom之类的变量添加前缀(如v_DateFrom)的习惯,这样就不会与表格中的列混淆。