gpt4 book ai didi

mysql - LEFT JOIN 删除行而不过滤原始表

转载 作者:行者123 更新时间:2023-11-28 23:31:11 27 4
gpt4 key购买 nike

下面的查询让我感到困惑。如果我执行 WHERE (inventory_to_pos.POSID IS NULL OR inventory_to_pos.POSID = ?) 并绑定(bind),它不会显示 products 表中的所有行inventory_to_pos 中可能存在也可能不存在的 POSID。当 LEFT JOIN-ing 表时,我是否应该从原始表中获取 所有 行,当我只对原始表进行过滤并使用 IS NULLLEFT JOIN'ed 表的任何条件下?

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.PRODUCTinventory_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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com