我有多对多的关系,我想选择特定字段的总和,以及所有必要的数据。我将通过代码解释我的案例。
首先,这是相关的表格结构:
CREATE TABLE `products` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,
`name` text,
`description` text,
`price` float,
`picture` varchar(255)
);
CREATE TABLE `orders_products` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,
`quantity` integer,
`status` boolean,
`product_id` integer,
`order_id` integer,
FOREIGN KEY(`product_id`) REFERENCES "products" ( "id" ),
FOREIGN KEY(`order_id`) REFERENCES "orders" ( "id" )
);
CREATE TABLE `orders` (
`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,
`created_at` datetime,
`updated_at` datetime,
`user_id` integer,
FOREIGN KEY(`user_id`) REFERENCES "users" ( "id" )
);
基本上我现在所做的就是:
select
"products".name,
"products".price,
"orders_products"."order_id",
"orders_products"."product_id"
from "products"
inner join "orders_products" on "orders_products"."product_id" = "products"."id"
where "orders_products"."order_id" in (1, 2)
这会产生以下结果:
name price order_id product_id
"coca cola" "2.35" "1" "1"
"snickers" "1.25" "1" "2"
"snickers" "1.25" "2" "2"
"popcorn" "1.19" "2" "3"
但是,如果我想“总结”价格,并根据order_id订购:
select
sum ("products".price) as _sum,
"products".name,
"products".price,
"orders_products"."order_id",
"orders_products"."product_id"
from "products"
inner join "orders_products" on "orders_products"."product_id" = "products"."id"
where "orders_products"."order_id" in (1, 2)
group by "orders_products"."order_id"
我得到以下结果:
_sum name price order_id product_id
"3.6" "snickers" "1.25" "1" "2"
"2.44" "popcorn" "1.19" "2" "3"
我真正想要的是:
name price order_id product_id _sum
"coca cola" "2.35" "1" "1" "3.6"
"snickers" "1.25" "1" "2" "3.6"
"snickers" "1.25" "2" "2" "2.44"
"popcorn" "1.19" "2" "3" "2.44"
这甚至可能吗?
答案 0 :(得分:3)
您可以做的是将每个sums
的{{1}}投影为派生表,然后将原始查询加回到派生表中,这样您就可以显示{{1} }作为每个订单的列:
order id
已在内部派生表上完成过滤,因此不需要重复。