需要mysql查询的帮助吗
我有一个mysql查询,它试图组合以下表:需要mysql查询的帮助吗,mysql,sql,Mysql,Sql,我有一个mysql查询,它试图组合以下表: TABLE: orders_products products_id orders_id products_quantity products_price TABLE: products products_id products_model 我需要一个查询,返回orders\u products表中每个产品的总销售额、每个产品id的总销售额以及产品型号。这是迄今为止我想到的最好的一款,它只是将所有东西都添加到同一个桶中: SELECT SUM
TABLE: orders_products
products_id
orders_id
products_quantity
products_price
TABLE: products
products_id
products_model
我需要一个查询,返回orders\u products表中每个产品的总销售额、每个产品id的总销售额以及产品型号。这是迄今为止我想到的最好的一款,它只是将所有东西都添加到同一个桶中:
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
在你的
where
之后添加groupby p.products\u id
,你会很好在你的where
之后添加groupby p.products\u id
,你会很好你需要使用groupby。检查此链接:您需要使用分组方式。检查此链接:+1您只需要按p.products\u id分组,在MySQL中,p.products\u model
在功能上依赖于products\u id
。没错,但大多数其他数据库确实需要它,并且假设这使得代码更加依赖MySQL。我更喜欢尽可能独立于数据库编写我的SQL,因此我认为将所有列包含在group by中是更好的做法。+1您只需要group by p.products\u id
在MySQL中,p.products\u模型
在功能上依赖于products\u id
,但是大多数其他数据库确实需要它,并且假设这使得代码更加依赖mysql。我更喜欢尝试将SQL编写为尽可能独立于数据库的,因此我认为将所有列包含在GROUPBY中是一种更好的做法。
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