【问题标题】:MySQL GROUP BY ignore or skip other null columnMySQL GROUP BY 忽略或跳过其他空列
【发布时间】:2018-06-16 20:45:57
【问题描述】:

我有一张桌子:

(id, storage_id, product_id, quantity, property_storage_group_id)

我需要最小数量,但是当prouct_id 是几个时,我需要忽略product_idproperty_storage_group_id = null

类似这样的:

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

但没有 id 22 和 id 27。

【问题讨论】:

    标签: mysql null record


    【解决方案1】:

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

    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 值的事实,因此它只返回不是NULLproperty_storage_group_id 的计数。如果该计数大于零,则第一个子查询为该product_id 选择所有带有property_storage_group_id IS NULL 的记录。最后,主查询排除了第二个查询返回的那些记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多