MySQL GROUP BY忽略或跳过其他空列

时间:2018-01-07 19:18:51

标签: mysql null record ignore

我有一张桌子:

(id, storage_id, product_id, quantity, property_storage_group_id)

enter image description here

我需要最小数量,但当prouct_id为几个时,我需要忽略product_id property_storage_group_id = null

这样的事情:

SELECT MIN(quantity), product_id
FROM storage_quantity
WHERE storage_id = 6 
GROUP BY product_id

但没有id 22,而且ID为27。

1 个答案:

答案 0 :(得分:0)

您可以使用子查询。试试这个:

SELECT MIN(s1.quantity), s1.product_id
FROM storage_quantity s1
WHERE s1.id NOT IN (SELECT s2.id
                    FROM storage_quantity s2
                    WHERE s2.product_id = s1.product_id
                      AND s2.storage_id = s1.storage_id
                      AND s2.property_storage_group_id IS NULL
                      AND (SELECT COUNT(s3.property_storage_group_id)
                         FROM storage_quantity s3
                         WHERE s3.product_id = s2.product_id
                           AND s3.storage_id = s2.storage_id
                        ) > 0
                   )
WHERE s1.storage_id = 6
GROUP BY s1.product_id

第二个子查询利用COUNT()函数自动忽略NULL值的事实,因此它只返回property_storage_group_id不是NULL的计数。如果该计数大于零,则第一个子查询将为property_storage_group_id IS NULL选择product_id的所有记录。最后,主查询排除了第二个查询返回的记录。