2011-04-15 252 views
0

我有试图在下表中结合了MySQL查询帮助:需要一个MySQL查询

TABLE: orders_products 
products_id 
orders_id 
products_quantity 
products_price 

TABLE: products 
products_id 
products_model 

我想返回销售总数的查询,对每个PRODUCT_ID销售总额,以及orders_products表中每个产品的product_model。这是我想出来的迄今最好的,它只是增加了什么东西都往同一桶:

SELECT 
    SUM(op.products_quantity) AS num_sold 
    ,SUM(op.final_price * op.products_quantity) 
    ,p.products_model 
FROM orders_products AS op 
JOIN products AS p 
WHERE p.products_id = op.products_id 

回答

4

添加group by p.products_idwhere后,你会好

+0

+1因为我喜欢它 – Smandoli 2011-04-15 04:13:11

+0

谢谢!我已经做了足够的查询,我应该知道这一点。 – user77413 2011-04-15 04:22:23

+0

@ user77413欢迎您 – Wes 2011-04-15 04:28:43

2
SELECT p.products_id, p.products_model, 
    SUM(op.products_quantity) AS num_sold 
    ,SUM(op.final_price * op.products_quantity) AS sales 
FROM orders_products AS op 
JOIN products AS p 
WHERE p.products_id = op.products_id 
GROUP BY p.products_id, p.products_model 
+0

+1的完整性 – Smandoli 2011-04-15 04:12:46

+0

+1您只需在MySQL中有'GROUP BY p.products_id','p.products_model'在功能上依赖于'products_id'。 – 2011-04-15 05:16:42

+0

确实如此,但大多数其他数据库确实需要它,并假设这使得代码更依赖于mysql。我更愿意尽可能地将我的SQL编写为独立于数据库的数据库,因此我认为将组中的所有列都包含在内是一种更好的做法。 – squawknull 2011-04-15 18:00:09