1

我尝试从数据库中获取最多 (30) 个订购的产品。

在表顺序中,我有一个列类型,其值为(1 OR -1)。1 表示有效的用户订单,-1 表示取消订单(在这种情况下,订单具有用户订单的参考 ID)

reference_id 是另一个订单的id(在同一个订单表中)| 一行引用另一行。

订单表:

id   |   reference_id  | type
---------------------------------- 
1    |                 | 1
---------------------------------- 
2    |                 | 1
---------------------------------- 
3    |   1             | -1
----------------------------------

产品表:

id   |   order_id   |   quantity
----------------------------------
a    |   1          |   4
----------------------------------
b    |   2          |   7
----------------------------------
a    |   3          |   2
----------------------------------

MySQL 查询:

SELECT *, sum(product.quantity) as quantity, count(*) as score 
FROM product LEFT JOIN order ON ( product.order_id=order.id ) 
WHERE (..?..) GROUP BY product.id ORDER BY score DESC LIMIT 30;

这将选择、汇总和计算所有订单中的所有产品。

但:

我正在寻找的是:

if(order.type < 0 ){
    product.quantity is in minus(-)
    (quantity of the Product in the referenced Order MINUS this.product.quantity)
}

如何在 SQL 语句中做到这一点?我尝试了很多东西但没有成功

根据要求的评论示例: 结果应该是按 product.id 分组的已订购产品的列表 大多数订购产品:

Product-id   |   quantity
-------------------------------------------
a            |   2 (in 2 Orders)
-------------------------------------------
b            |   7 (in 1 Order)
-------------------------------------------
c            |   12 (in 3 Orders)
-------------------------------------------
...etc.

非常感谢

4

3 回答 3

1

这将计算订单并将总和设为 9

这个查询在这里工作 http://www.sqlfiddle.com/#!2/9c3a1/6/0

 SELECT Sum(orders.type * products.quantity) AS quant, 
       count(products.id) as count,
       products.id 
FROM   orders 
       INNER JOIN products 
               ON orders.id = products.order_id 

如果您想要 2 的数量(已订购 2 个产品)

SELECT Sum(orders.type * products.quantity) AS quant, 
       count(distinct products.id) as count,
       products.id 
FROM   orders 
       INNER JOIN products 
               ON orders.id = products.order_id 

这里的计数将是 1,总和将是 7 和 2(根据您的最新编辑)

SELECT products.id, Sum(orders.type * products.quantity) AS quant, 
       count(distinct orders.id) as count
FROM   orders 
       INNER JOIN products 
               ON orders.id = products.order_id 
GROUP BY products.id

这正是您所要求的

于 2013-08-26T11:42:52.760 回答
1

我感谢大家的评论和回答。但我最终得到了这个声明:

        SELECT *,
        SUM(o.type * p.quantity ) as quantity, 
        COUNT(*) as score 
        FROM product AS p 
        LEFT JOIN order AS o 
        ON p.order_id = o.id
        GROUP BY p.id ORDER BY quantity DESC LIMIT 30;
于 2013-08-26T12:49:46.250 回答
0

尝试这样的事情:

 SELECT sum(case when orders.type < 0 
       THEN products.quantity * -1
       else products.quantity end) as quantity,
  products.id,      
  count(products.id) as score,     
 FROM products LEFT JOIN orders ON ( products.order_id=orders.id )
 ORDER BY score DESC LIMIT 30;

SQL小提琴

于 2013-08-26T11:58:53.290 回答