【问题标题】:counting the most sold products from mysql计算 mysql 中最畅销的产品
【发布时间】:2013-12-27 12:37:52
【问题描述】:

我正在尝试通过 mysql 查询来获得最畅销的产品列表。问题是即使在我使用 count 之后它仍然可以获取所有数据。

select 
    mf.*,
    od.*,
    count(od.product_id) as product_count
from masterflight mf , 
    order_details od 
where od.product_id=mf.ProductCode 
group by od.product_id 
order by product_count

这里的masterflight 是存储产品详细信息及其 id 的表。而order_details 是存储每个单独销售的产品记录的表格。我试图输入一个逻辑,假设 ID 为 2 的产品被售出 4 次,每次它都有一个单独的条目,然后我会计算那些使用 COUNT 的产品,然后显示它似乎在工作.

【问题讨论】:

  • 你得到的结果是什么,应该是什么?

标签: mysql


【解决方案1】:

尝试一些更整洁的东西:

select
    mf.ProductCode,
    count(od.*) as product_count
from
    order_details od
    inner join masterflight mf on
        od.product_id = mf.ProductCode
group by
    mf.ProductCode
order by product_count desc

问题是你选择了所有od,但你没有按它分组,所以你只是得到了所有的订单行,这对你没有任何帮助。我应该注意到 MySQL 是唯一允许这种行为的主要 RDBMS 之一——而且它令人困惑且难以调试。我建议不要使用该特定功能。作为一般规则,如果您选择了一个列但没有聚合(例如-sumavgmin 等),那么您需要在 group by 子句中使用它.

【讨论】:

    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    相关资源
    最近更新 更多