このようなものが欲しいですか?
SELECT * FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS)
carts
INNER JOIN は、carts_products
適合するエントリがある場所でのみ結合します。
===編集===
単一のユーザーを返すには、最初の行を次のように変更できます。
SELECT DISTINCT Users.* FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS TO INCLUDE)
AND cart_products.product_id NOT IN (LIST OF PRODUCT IDS TO EXCLUDE)
または、サブクエリで IN を使用します。
SELECT u.* from Users u WHERE u.id IN
(
SELECT Users.id FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS)
)
最初のオプションの方が少し最適かもしれないと思いますが、クエリプランナーによって最適化されて同じになる可能性は十分にあります。確認するには、いくつかのベンチマークを実行する必要があります。
===編集2 ===
それで、あなたは交差点を求めていると思いますか?
SELECT DISTINCT Users.* FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS TO INCLUDE)
INTERSECT
SELECT DISTINCT Users.* FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id NOT IN (LIST OF PRODUCT IDS TO EXCLUDE)
これも同じだと思います...
SELECT DISTINCT Users.* FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS TO INCLUDE)
EXCEPT
SELECT DISTINCT Users.* FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS TO EXCLUDE)
どの SQL 実装が EXCEPT を許可するかはわかりませんが、別の方法として、ここで説明されているように LEFT JOIN を使用することです: http://en.wikipedia.org/wiki/Set_operations_(SQL)#EXCEPT_operator
===編集3 ===
SELECT u.* from Users u WHERE u.id IN
(
SELECT Users.id FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS TO INCLUDE)
)
AND u.id NOT IN
(
SELECT Users.id FROM Users
INNER JOIN carts on carts.user_id = Users.id
INNER JOIN cart_products on carts.id = carts_products.cart_id
WHERE cart_products.price > X and cart_products.price < Y
AND cart_products.product_id IN (LIST OF PRODUCT IDS TO EXCLUDE)
)