MySql订单By和COUNT()

时间:2014-08-27 17:17:45

标签: php mysql sql

我正在尝试计算购买商品的次数。但是,我还有一个类别表,也在我的查询中计算,这当然导致错误的数据。如何在一个表中计算我需要的行并仅获得这些结果?

MySQL查询

    select 
    `inventory`.`on_sale`,
    `inventory`.`id`,
    `inventory`.`sku`,
    `inventory`.`name`,
    `inventory`.`price`,
    `inventory_categories`.`category`,
    `inventory`.`stock_quantity`,
    COUNT(orders_product.sku) as skuCount
from
    `inventory`
        left join
    `orders_product` ON `orders_product`.`sku` = `inventory`.`sku`
        left join
    `inventory_categories` ON `inventory`.`sku` = `inventory_categories`.`sku`
group by `inventory_categories`.`category`
order by `skuCount` desc
limit 10000

很难显示我的所有记录,但它基本上是这样的:

orders_product.sku = ORDER1234 & ORDER1234 & ORDER891010

inventory_categories.(id)category = (cat1)ORDER1234 & (cat1a)ORDER1234 & (cat1b)ORDER1234 & (cat2)ORDER891010

所以在我桌上的表格中显示skuCount = 5&分别代表2和2的所需结果。分别为1。如果我没有具有该inventory.id的订单,那么它显示0是正确的,但是一旦订单通过,它将计算该订单PLUS所有等于该sku的类别。

如果我从join语句中删除inventory_categories,它可以正常工作。但是,在查询中需要它以用于记录目的。

2 个答案:

答案 0 :(得分:1)

以下查询如何:

SELECT i.on_sale, i.id, i.sku, i.name, i.price, ic.category, i.stock_quantity, 
(
  SELECT COUNT(*)
  FROM orders_product op
  WHERE op.sku = i.sku
) AS skuCount
FROM inventory i
LEFT JOIN inventory_categories ic ON i.sku = ic.sku
ORDER BY skuCount DESC
LIMIT 10000

答案 1 :(得分:0)

SELECT A.on_sale, a.id, a.sku,a.name,a.price, a.stock_Quantity, skucount, count(ic.category) as CatCount
FROM 
( SELECT 
    `inventory`.`on_sale`,
    `inventory`.`id`,
    `inventory`.`sku`,
    `inventory`.`name`,
    `inventory`.`price`,
    `inventory`.`stock_quantity`,
    COUNT(orders_product.sku) as skuCount
  FROM `inventory`
  LEFT JOIN `orders_product` 
    ON `orders_product`.`sku` = `inventory`.`sku`
  GROUP BY `inventory`.`on_sale`, `inventory`.`id`,
    `inventory`.`sku`, `inventory`.`name`,
    `inventory`.`price`, `inventory`.`stock_quantity`) A
LEFT JOIN  `inventory_categories` IC
  ON `inventory`.`sku` = `inventory_categories`.`sku`
GROUP BY A.on_sale, a.id, a.sku,a.name,a.price, a.stock_Quantity, skucount
OREDER BY `skuCount` desc
LIMIT 10000

您必须首先获得包含SKU计数的结果集,然后加入表格。