我有一张桌子:
(id, storage_id, product_id, quantity, property_storage_group_id)
我需要最小数量,但当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。
答案 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
的所有记录。最后,主查询排除了第二个查询返回的记录。