在查询中左右连接

Hos*_*Aly 0 mysql sql join

一位朋友向我请求帮助,建立一个查询,显示每个月的每一天销售的每个模型的数量,在特定日期没有特定模型的销售件时显示零,即使没有任何项目模特在那天出售.我想出了下面的查询,但它没有按预期工作.我只获得已售出的模型的记录,我不知道为什么.

select days_of_months.`Date`,
       m.NAME as "Model",
       count(t.ID) as "Count"
  from MODEL m
  left join APPLIANCE_UNIT a on (m.ID = a.MODEL_FK and a.NUMBER_OF_UNITS > 0)
  left join NEW_TICKET t on (a.NEW_TICKET_FK = t.ID and t.TYPE = 'SALES'
and t.SALES_ORDER_FK is not null)
 right join (select date(concat(2009,'-',temp_months.id,'-',temp_days.id)) as "Date"
               from temp_months
              inner join temp_days on temp_days.id <= temp_months.last_day
              where temp_months.id = 3 -- March
             ) days_of_months on date(t.CREATION_DATE_TIME) =
date(days_of_months.`Date`)
 group by days_of_months.`Date`,
       m.ID, m.NAME
Run Code Online (Sandbox Code Playgroud)

我创建了临时表temp_months,temp_days以便获得任何月份的所有日期.我正在使用MySQL 5.1,但我正在努力使查询符合ANSI标准.

Qua*_*noi 6

您应该使用CROSS JOIN日期和模型,以便每个日模型对只有一条记录,无论如何,然后是LEFT JOIN其他表格:

SELECT  date, name, COUNT(t.id)
FROM    (
        SELECT ...
        ) AS days_of_months
CROSS JOIN
        model m
LEFT JOIN
        APPLIANCE_UNIT a
ON      a.MODEL_FK = m.id
        AND a.NUMBER_OF_UNITS > 0
LEFT JOIN
        NEW_TICKET t
ON      t.id = a.NEW_TICKET_FK
        AND t.TYPE = 'SALES'
        AND t.SALES_ORDER_FK IS NOT NULL
        AND t.CREATION_DATE_TIME >= days_of_months.`Date`
        AND t.CREATION_DATE_TIME < days_of_months.`Date` + INTERVAL 1 DAY
GROUP BY
        date, name
Run Code Online (Sandbox Code Playgroud)

你做的方式,现在你得到NULL的在model_id你没有销售额的日子里,它们组合在一起.

注意JOIN条件:

AND t.CREATION_DATE_TIME >= days_of_months.`Date`
AND t.CREATION_DATE_TIME < days_of_months.`Date` + INTERVAL 1 DAY
Run Code Online (Sandbox Code Playgroud)

代替

DATE(t.CREATION_DATE_TIME) = DATE(days_of_months.`Date`)
Run Code Online (Sandbox Code Playgroud)

这将有助于您的查询sargable(通过索引优化)