MySQL 左连接在没有数据的情况下填充值

标签 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

最佳答案

您可以通过使用交叉联接来获取该范围内的所有可能日期来实现此目的。然后,您可以将此字段用于左连接选择:

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)的习惯,这样它们就不会与表中的列混淆。

关于MySQL 左连接在没有数据的情况下填充值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22635005/

相关文章:

mysql - 需要数据库两个月前每小时的数据

mysql - 在 Rails 中拥有持久内存哈希的最佳方法?

php - 为相同的值插入多行 - SQL

mysql - 在 MySQL 中为 false 或 false = true?非常奇怪的行为

php - 无法使用 hhvm 找到驱动程序 MySQL

php - 使用日期时间的最新记录

Python MYSQL-connector 备份创建

mysql - 如果第二个表满足要求,则从多个表中选择数据

mysql - 在计算列内项目的出现次数后,在 MySql 表列上应用公式。

mysql - 如何在mysql中的同一个表上执行内连接