如何填补行间的间隙?我使用表日历,但我的查询似乎不正确。结果没有显示差距..
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
答案 0 :(得分: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_product
的值为空,但您要过滤t2.id_product = 11
。因此,null
记录永远不会与11
匹配,这就是为什么他们被排除在外。
答案 1 :(得分: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
您必须决定要允许哪些表为空。
答案 2 :(得分: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