需要有关mysql查询的帮助

时间:2011-04-15 04:00:47

标签: mysql sql

我有一个试图合并以下表格的mysql查询:

TABLE: orders_products
products_id
orders_id
products_quantity
products_price

TABLE: products
products_id
products_model

我想要一个查询,它返回orders_products表中每个product_id的每个product_id和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

3 个答案:

答案 0 :(得分:4)

group by p.products_id之后添加where,您就会很好

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

答案 2 :(得分:0)

您需要使用GROUP BY。请检查此链接:http://www.w3schools.com/sql/sql_groupby.asp