以下查询让我感到困惑。如果我执行 WHERE (inventory_to_pos.POSID IS NULL OR inventory_to_pos.POSID = ?)
并绑定(bind),它不会显示products
表中的所有行inventory_to_pos
中可能存在也可能不存在的 POSID
。当LEFT JOIN
-ing一个表时,当我只过滤原始表并使用IS NULL
时,我是否应该从原始表中获取所有行code> 对于 LEFT JOIN
的表有任何条件吗?
SELECT products.ID,products.NAME,products.VOLUME,productcombinations.PRODUCTID,productcombinations.PART,inventory_to_pos.FULLCOUNT
FROM products
LEFT JOIN productcombinations ON products.ID = productcombinations.PARTOF
LEFT JOIN inventory_to_pos ON products.ID = inventory_to_pos.PRODUCT
WHERE products.INVENTORY = 1
AND products.AVAILABLE = 1
AND products.ID > 0
AND (inventory_to_pos.POSID IS NULL OR inventory_to_pos.POSID = ?);
如果给定产品和 POSID 不存在 inventory_to_pos.PRODUCT
和 inventory_to_pos.POSID
,则不会给我任何行。为什么?
最佳答案
将所有相关的 invetory_to_pos
子句移至 LEFT JOIN,即:
SELECT
products.ID,
products. NAME,
products.VOLUME,
productcombinations.PRODUCTID,
productcombinations.PART,
inventory_to_pos.FULLCOUNT
FROM
products
LEFT JOIN productcombinations ON products.ID = productcombinations.PARTOF
LEFT JOIN inventory_to_pos ON products.ID = inventory_to_pos.PRODUCT AND (
inventory_to_pos.POSID IS NULL
OR inventory_to_pos.POSID = ?
)
WHERE
products.INVENTORY = 1
AND products.AVAILABLE = 1
AND products.ID > 0
关于mysql - LEFT JOIN 删除行而不过滤原始表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37299983/