带有引用列的MySQL JOIN表

时间:2013-08-26 10:47:27

标签: mysql join

我尝试从数据库中获取最多(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;

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

BUT:

我在寻找的是:

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

如何在SQL语句中执行此操作? 我尝试过somany但没有成功

根据请求的评论

示例: result应该是按product.id分组的有序产品的列表 大多数有序产品:

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

3 个答案:

答案 0 :(得分: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,Sum将为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

这完全符合您的要求

答案 1 :(得分: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;

答案 2 :(得分: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 Fiddle