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

标签 mysql left-join

以下查询让我感到困惑。如果我执行 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.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/

相关文章:

mysql - 棘手的 MySQL ORDER BY 问题

php - PHP/MYSQL创建表/insert数据

php - 如何从 PHP 数组中的 Mysql 表中获取所有匹配的行

javascript - Linq JS 连接语法

MySQL - 将表与主表连接两次

php - 如何在网站中创建过滤器

php - 无法通过 PHP 将数据添加到我的 MySQL 数据库

mysql - 在 mysql 中从主字段查找子字段时遇到问题

sql - SQL-内部联接2个表,但如果1个表为空则返回全部

sql - 当 PostgreSQL 中特定字段的平均值为空时如何分配零(0)