【发布时间】:2020-09-25 02:55:12
【问题描述】:
我正在尝试为商店中的订单创建两个查询。基本上我有一个产品订单清单。每个订单可以有多个产品,每个产品都可以存储。我要找:
-
所有产品都在存储中的订单(订单表加入 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
非常感谢您的帮助!
【问题讨论】:
-
不是解决方案,但我注意到:“至少有一个在存储中”=>
where order_products.in_storage > 0 -
啊,我忘了提到 in_storage 它是 1/0,就像真/假一样 - 这不是数量。 (这是客户数据库,我无法改变这个想法)
标签: mysql