MySQL JOIN不返回正确的行集

时间:2017-02-06 09:58:20

标签: mysql sql join left-join

我遇到了正在运行的加入查询的问题。出于某种原因,我只返回59,596行而不是68,058行。

我尝试了各种LEFT / RIGHT / INNER JOINS但没有运气。我有双重检查表CC,可以确认指定范围有68,059行数据。但是,派生表XX的行数较少。

我想返回表CC中的所有行,尽管该行是否在表XX中。

以下是我正在使用的查询以及表结构:

    SELECT 

        CC.entity_code 'Entity Code 2'    

    ,       (SELECT MAX(action_date) AS secMaxDate 
            FROM 
            sys_reference.entities_visited DD

            WHERE 
            entity_code = XX.storeCode 
            AND     action_date < XX.maxDate) ' Previous Visit Date'
    ,       XX.maxDate  'Latest Visit Date'
    ,       cycle_end_date 'Cycle End Date'
    ,       WEEK(cycle_end_date,1)  'Cycle Week'
    ,   CASE 

            WHEN XX.visits > 10 THEN 0

            ELSE XX.visits

        END 'Total Visits (28 Days)'
    ,   CASE 
            WHEN XX.maxDate = MAX(CC.action_date) THEN 1
            ELSE 0
        END AS 'Call Cycle Compliance' 
    FROM 
        sys_reference.call_cycles CC
    LEFT JOIN        
        (SELECT 
            BB.entity_code AS storeCode
        ,   MAX(action_date) AS maxDate
        ,   MAX(cycle_end_date) AS cycle_end_date
        ,   (SELECT COUNT(AA.entity_code) FROM sys_reference.entities_visited AA WHERE AA.action_date BETWEEN '2017-01-01' AND '2017-01-31' AND AA.entity_code = BB.entity_code) AS visits
        FROM 
            sys_reference.entities_visited BB
GROUP BY 
            BB.entity_code
        ,   WEEK(BB.action_date,1)) AS XX        
    ON  
        CC.entity_code = XX.storeCode
    WHERE
        CC.action_date BETWEEN '2017-01-01' AND '2017-01-31'
    AND     YEARWEEK(cycle_end_date,1) BETWEEN YEARWEEK('2017-01-01') AND YEARWEEK('2017-01-31')
    GROUP BY 
        CC.entity_code
    ,   WEEK(cycle_end_date,1)
    LIMIT 0,100000;

调用周期表

entity_code | action_date| cycle_end_date   
------------+------------+--------------- 
108792      |2017-01-07  |2017-01-11    
108792      |2017-01-10  |2017-01-11  
108792      |2017-01-12  |2017-01-18  
108793      |2017-01-08  |2017-01-11    
108795      |2017-01-06  |2017-01-11    
108796      |2017-01-05  |2017-01-11    
108795      |2017-01-13  |2017-01-18  
108792      |2017-01-07  |2017-01-11   
108792      |2017-01-14  |2017-01-18    
108793      |2017-01-14  |2017-01-18    
108796      |2017-01-16  |2017-01-18

实体访问表

entity_code | visit_date | cycle_end_date   
------------+------------+--------------- 
108792      |2017-01-07  |2017-01-11    
108793      |2017-01-08  |2017-01-11    
108795      |2017-01-06  |2017-01-11    
108796      |2017-01-05  |2017-01-11    
108795      |2017-01-13  |2017-01-18    
108792      |2017-01-14  |2017-01-18    
108793      |2017-01-14  |2017-01-18    
108796      |2017-01-16  |2017-01-18

从示例数据中,我需要从Call Cycle Table返回所有行。

0 个答案:

没有答案