你想要这样的东西吗?
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)
INNER JOIN 只会在有一个carts
和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===
所以现在我认为你要的是一个 INTERSECTION?
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)
)