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

时间:2016-05-18 12:42:05

标签: mysql left-join

以下查询让我感到困惑。如果我productsWHERE (inventory_to_pos.POSID IS NULL OR inventory_to_pos.POSID = ?)绑定POSID可能存在或不存在inventory_to_pos,那么会显示LEFT JOIN表格中的所有行。当IS NULL表格时,我不应该从原始表格中获取所有行,当我只对原始表格进行过滤并在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 = ?); inventory_to_pos.PRODUCT 1}}'ed tables?

inventory_to_pos.POSID

如果给定产品和POSID不存在- (void) calculateSize { NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Event"]; NSArray *data = [self.managedObjectContext executeFetchRequest:request error:nil]; NSLog(@"Size of %@: %zd", NSStringFromClass([data class]), malloc_size((__bridge const void *) data)); int totalSize = 0; for(NSManagedObject *object in data) { totalSize += malloc_size((__bridge const void *) object); } NSLog(@"Managed Object Size total:%d", totalSize); } wp-config.php,则不会给出任何行。为什么呢?

1 个答案:

答案 0 :(得分:1)

将所有相关的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