0

MYSQL

我想根据表单复选框中的项目过滤“订单”。

例如,我检查了 ITEM A + ITEM B ,但没有检查 ITEM C

订单 1

项目 A

订单 2

项目 B

订单 3

项目 A

项目 B

项目 C

订单 4

项目 A

项目 B

我想要的是:

ORDER 1 & ORDER 2 & ORDER 4,但不是 ORDER 3,因为这也有 C 项

我这样的查询

SELECT
P.id as product_id,P.name as product_name,
O.id as order_id,O.group_id,O.payment_date,O.payment_type_id,I.quantity,
M.name,M.surname,M.email
FROM tbl_orders O
LEFT JOIN tbl_order_items I on I.order_id = O.id
LEFT JOIN tbl_products P on P.id = I.product_id
LEFT JOIN tbl_members M on M.id = O.member_id
WHERE
     I.product_id in (1044,1129,20976,16775)
AND
     O.status_id = 311 and O.payment_status_id = 349

谢谢

4

1 回答 1

1

我猜核心问题是您想要排除具有任何未检查值的订单,并包含至少具有一个已检查值的订单。

SELECT
P.id as product_id,P.name as product_name,
O.id as order_id,O.group_id,O.payment_date,O.payment_type_id,I.quantity,
M.name,M.surname,M.email
FROM tbl_orders O -- start with orders

-- add in the items, but use INNER to avoid orders that do not have
-- at least one order_item whose id was checked
INNER JOIN tbl_order_items I on I.order_id = O.id
           AND I.product_id in (1044,1129,20976,16775)
-- left join in the items which were NOT checked.  If there are any, the
-- rows will have bad product ids in them.
-- But if there ARE NOT any bad items in the order, 
-- then there will only be one row with NULL for BADITEMS.product_id
LEFT JOIN tbl_order_items BADITEMS on BADITEMS.order_id = O.id
           AND BADITEMS.product_id NOT in (1044,1129,20976,16775)
-- Pull in the product information
INNER JOIN tbl_products P on P.id = I.product_id
-- Pull in member information
LEFT JOIN tbl_members M on M.id = O.member_id
WHERE
     -- the inner join has already insured that we only get orders
     -- that have checked items.
     -- To remove the orders that ALSO had unchecked items,
     -- We take only rows where the BADITEMS join failed.
     BADITEMS.product_id IS NULL
AND
     O.status_id = 311 and O.payment_status_id = 349
于 2012-06-14T23:01:46.670 回答