2

如何填补行之间的空白?我正在使用表格日历,但我的查询似乎不正确。结果没有显示差距..

SELECT calendar.datefield, t2.*
    FROM store_relation t1,store t3, store_product t2
            RIGHT JOIN calendar ON (DATE(t2.created) = calendar.datefield)
            WHERE (calendar.datefield BETWEEN ('2012-07-15') and ('2012-07-20'))
    AND t1.id_store_a = 1
    AND t1.id_store_b = t2.id_store
    AND t3.id = t2.id_store
    AND t2.id_product = 11
    ORDER By t2.price

结果:

datefield   |   id_product   |   id_store   |   created
2012-07-15      1                1              2012-07-15
2012-07-18      1                1              2012-07-18
2012-07-20      1                1              2012-07-20
2012-07-20      1                1              2012-07-20

我在等结果

datefield   |   id_product   |   id_store   |   created
2012-07-15      1                1              2012-07-15
2012-07-16      null             null           null
2012-07-17      null             null           null
2012-07-18      1                1              2012-07-18
2012-07-19      null             null           null
2012-07-20      1                1              2012-07-20
2012-07-20      1                1              2012-07-20
4

3 回答 3

2

当您有一个 LEFT/RIGHT JOIN 并且您正在筛选可选包含的表时,该WHERE子句会将这些记录排除在外。您需要包含一个允许RIGHT JOIN丢失左侧部分的条件:

WHERE (calendar.datefield BETWEEN ('2012-07-15') and ('2012-07-20'))
AND
(
   (t1.id_store_a = 1
   AND t1.id_store_b = t2.id_store
   AND t3.id = t2.id_store
   AND t2.id_product = 11)
   OR
   (t2.id_product is NULL)
)

例如,如果您查看预期输出,则 的值为id_productnull,但您正在过滤t2.id_product = 11. 所以null记录永远不会匹配11,这就是它们被排除在外的原因。

于 2012-07-26T18:17:23.027 回答
1

WHERE您正在引用子句左侧的一些列。尝试显式添加OR NULL条件。例如:

SELECT calendar.datefield, t2.*
FROM store_relation t1,store t3, store_product t2
        RIGHT JOIN calendar ON (DATE(t2.created) = calendar.datefield)
        WHERE (calendar.datefield BETWEEN ('2012-07-15') and ('2012-07-20'))
AND ((t1.id_store_a = 1
        AND t1.id_store_b = t2.id_store
        AND t3.id = t2.id_store
        AND t2.id_product = 11)
    OR (t1.id IS NULL AND t2.id IS NULL AND t3.id IS NULL))
ORDER By t2.price

您必须决定要允许哪些表为空。

于 2012-07-26T18:17:39.350 回答
0

好的,我明白了...谢谢你给我新的想法

SELECT calendar.datefield as DATE, t2.*
FROM store_relation t1,store t3, store_product t2
    RIGHT JOIN calendar ON (DATE(t2.created) = calendar.datefield)
    WHERE (calendar.datefield BETWEEN ('2012-07-15') and ('2012-07-27'))
AND ((t1.id_store_a = 1
    AND t1.id_store_b = t2.id_store
    AND t3.id = t2.id_store
    AND t2.id_product = 11)
OR (t2.id_product IS NULL))
GROUP BY DATE
于 2012-07-26T18:51:50.350 回答