Дано. (урезанный вариант)
Orders:
id
OrderProducts:
id
order_id
product_id
delivery_complete
Products:
id
category_id
В обоих условиях OrderProducts не должны урезаться из выборки(из join) как по ним идет калькуляция общенй суммы и т.п.
1) Простой вариант
Нужно получить все заказы, у которых все продукты delivery_complete=1
2) сложный вариант
обязательное условие, чтоб у заказа все продукты с products.`category_id` != 9 были orders_products.delivery_complete = 1
и при этом хотя бы один
orders_products.delivery_complete = 0 AND products.`category_id` = 9
Решил вопрос так(сложный вариант), но этот пипец коряво
SELECT
`orders`.*,
`products_count`,
`products_available`,
`products_ek_count`,
`products_ek_sum`,
`products_in_stock`,
(SELECT
COUNT(orders_products.id)
FROM
orders_products
LEFT JOIN products
ON orders_products.`products_id` = products.id
WHERE orders_products.orders_id = `orders`.`id`
AND orders_products.delivery_complete = 1
AND products.`category_id` != 9) AS delivery_complete_not_ww_products,
(SELECT
COUNT(orders_products.id)
FROM
orders_products
LEFT JOIN products
ON orders_products.`products_id` = products.id
WHERE orders_products.orders_id = `orders`.`id`
AND products.`category_id` != 9) AS not_ww_products
FROM
`orders`
INNER JOIN `orders_products`
ON `orders_products`.`orders_id` = `orders`.`id`
INNER JOIN `products`
ON `orders_products`.`products_id` = `products`.`id`
INNER JOIN
(SELECT
orders_id,
COUNT(id) AS products_count,
SUM(delivery_complete) AS products_available,
SUM(ek) AS products_ek_sum,
SUM(IF(in_stock > 0, 1, 0)) AS products_in_stock,
SUM(IF(ek > 0, 1, 0)) AS products_ek_count
FROM
orders_products
GROUP BY orders_id) AS sq_products_count
ON `orders`.`id` = `sq_products_count`.`orders_id`
GROUP BY `orders`.`id`,
HAVING delivery_complete_not_ww_products = not_ww_products
AND products_count > not_ww_products
AND products_count > products_available
AND not_ww_products > 0
UPDATE
легкий вариант готов
SELECT
`orders`.*
FROM
`orders`
INNER JOIN `orders_products` ON `orders_products`.`orders_id` = `orders`.`id`
INNER JOIN `products` ON `orders_products`.`products_id` = `products`.`id`
WHERE `orders`.status NOT IN ('ERLEDIGT', 'STORNO')
AND orders.id IN (SELECT `orders_id`
FROM `orders_products`
INNER JOIN `products` ON `orders_products`.`products_id` = `products`.`id`
WHERE orders_products.delivery_complete = 1 AND products.`category_id` != 9)
GROUP BY `orders`.`id`
Но теперь нужно добавить условие сложного варианта
получается обязательное условие, чтоб у заказа все продукты с products.`category_id` != 9 были orders_products.delivery_complete = 1
и при этом хотя бы один
orders_products.delivery_complete = 0 AND products.`category_id` = 9