mysql查询返回null行

时间:2016-01-07 22:08:24

标签: mysql

我想执行此查询但它在表空时返回空行。当SUM(products.sale_price)/COUNT(orders.id) AS avg_price_rang 不在查询

中时,它正在工作
SELECT
    products.brand_id,
    (SELECT
        category_brands.name
     FROM
        category_brands
     WHERE
        category_brands.id=products.brand_id
    ) AS brand,
    products.material_id,
    (SELECT
        category_materials.material
     FROM
        category_materials
     WHERE
        category_materials.id=products.material_id
    ) AS material,
    orders.color_code,
    SUM(products.sale_price)/COUNT(orders.id) AS avg_price_rang
FROM
    orders
INNER JOIN
    products
ON
    orders.prodcut_id = products.id

2 个答案:

答案 0 :(得分:1)

我认为它缺少GROUP BY products.brand_id

答案 1 :(得分:1)

当没有行时选择SUM会导致返回所有NULL的行。

MySQL 5.5 Reference Manual
12.17.1 GROUP BY (Aggregate) Functions

  

如果在不包含GROUP BY子句的语句中使用组函数,则它等同于对所有行进行分组。有关更多信息,请参见第12.17.3节“GROUP BY的MySQL处理”。

使用:

query
HAVING avg_price_rang IS NOT NULL

SELECT * FROM (
    query
    ) dummy
WHERE avg_price_rang IS NOT NULL