mysql正确加入和条件

时间:2012-07-30 12:15:57

标签: mysql sql join

在下面的查询中,我正在连接表日历和第二个表,我需要为查询指定一些参数。

表的连接是在字段calendar.datefield和store_product.created

上执行的

问题是我按id_store = 3进行过滤,并且07/20/2012 store_product表记录中的另一行有id_store = 4,因此查询不会带来结果。有没有办法将此结果显示为NULL,强制mysql忽略这种情况?

结果:(包含日期2012-07-20的行未显示,因为它有其他id_store)

DATE            price
2012-07-17      NULL
2012-07-18      700.00
2012-07-19      NULL
2012-07-21      NULL
2012-07-22      NULL
2012-07-23      NULL

我想显示

     DATE               price
     2012-07-17         NULL
     2012-07-18         700.00
     2012-07-19         NULL
->>> 2012-07-20         NULL
     2012-07-21         NULL
     2012-07-22         NULL
     2012-07-23         NULL

查询:

set @id_store = 3;
set @id_product = 11;

SELECT 
calendar.datefield as DATE,
t1.price
FROM
store_product t1
    RIGHT JOIN
calendar ON (DATE(t1.created) = calendar.datefield)
WHERE
(calendar.datefield BETWEEN ('2012-07-17') and ('2012-07-23'))
    AND (t1.id_store = @id_store OR t1.id_store is NULL)
    AND (t1.id_product = @id_product OR t1.id_product is NULL)
    AND (t1.created = (select 
        max(f2.created)
    from
        store_product f2
    where
        f2.id_store = t1.id_store
            and f2.id_product = t1.id_product
            and DATE(t1.created) = DATE(f2.created))
    OR t1.created is NULL)
GROUP BY DATE , t1.id_store , t1.id_product

1 个答案:

答案 0 :(得分:0)

该记录无法显示(显然),因为您只过滤ID为3的商店.RIGHT JOIN执行它应该执行的操作,然后使用过滤器进一步减少结果。我认为你必须在主代码中处理这个问题,为你添加“缺失”记录。我不认为SQL可以做你想做的事。