查询HAVING MAX()没有按预期工作

时间:2018-06-11 10:24:25

标签: mysql sql database mysqli having-clause

我在数据库中有四个表。表格如下:

SELECT x.category,x.amount
    FROM (SELECT category_name as category, SUM(amount) as amount FROM 
          Category c, Product pr, Purchase pu WHERE pr.product_id = 
          pu.product_id and c.category_id = pr.category_id GROUP BY 
          category_name) x
    GROUP BY x.category
    HAVING MAX(x.amount);

我想选择购买次数最多的类别名称。这是我到目前为止所做的,但我无法得到我想要的结果

{{1}}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

据推测,你想要这样的东西:

SELECT c.category_name as category, SUM(amount) as amount
FROM Category c JOIN
     Product pr
     ON c.category_id = pr.category_id JOIN
     Purchase pu 
     ON pr.product_id = pu.product_id
GROUP BY category_name
ORDER BY SUM(amount) DESC
LIMIT 1;

从不FROM子句中使用逗号。 始终使用正确,明确,标准的JOIN语法。