我正在尝试为商店中的订单创建两个查询。基本上我有一个产品订单清单。每个订单可以有多个产品,每个产品都可以存储。我想找到:
存储所有产品的订单(订单表连接 order_products 表,其中所有找到的行必须将 in_storage 设置为 1(真/假 - 它不是数量)
至少有一种产品在存储中的订单(但不是全部在;所以加入的 order_products 表必须至少有两种产品,其中至少有一种在存储中;如果两者都将 in_storage 设置为 1 - 不满足条件并且不会结果显示)
预期结果是订单 ID(唯一/分组)上的列表。
我在 db fiddle 中创建了非常简单的版本:
https://www.db-fiddle.com/f/nfa2ooHt3FWmKQM9DmmPEA/0
CREATE TABLE orders (
id INT
);
INSERT INTO orders (id) VALUES (1);
INSERT INTO orders (id) VALUES (2);
CREATE TABLE order_products (
id_product INT,
id_order INT,
in_storage INT
);
INSERT INTO order_products (id_product, id_order, in_storage) VALUES (1,1,1); # product in storage -order id 1
INSERT INTO order_products (id_product, id_order, in_storage) VALUES (2,1,0); # product not in storage - order id 1
INSERT INTO order_products (id_product, id_order, in_storage) VALUES (3,2,1); # product in storage - order id 2
INSERT INTO order_products (id_product, id_order, in_storage) VALUES (4,2,1); # product in storage - order id 2
#Query first - find orders WHERE has all products in storage
#expected result - order with id 2
#Query second - find orders WHERE has partial products in stronage - minimum one product marked as in_storage but not all
#expected result - order with id 1 (first product in storage; second not)
SELECT id FROM orders
left join order_products on orders.id = order_products.id_order
where order_products.in_storage = 1
GROUP BY id
非常感谢您的帮助!