我有一个包含许多表的数据库:
customer
------
id
name
customer_order
------
order_id
order_cost
customer_id
customer_order_line
------
order_line_id
order_id
order_line_product_id
product
------
product_id
product_name
product_cost
我想做的是选择所有尚未购买某个特定项目的客户,例如,如果我输入“ apple”作为变量输入,我想返回所有尚未购买苹果的客户。
这只是一种情况。
我花了几天的时间尝试执行此操作,例如将所有产品合并到一个字段中并使用NOT LIKE @searchVariable
之类的方法,但由于始终如一地考虑了来自customer_order_line
表。
有人可以为此指出正确的方向吗?
欢呼
答案 0 :(得分:5)
有几种方法。这是使用C:\Documents\work\region\testProject\build (master -> origin)
λ source.exe
Opening serial port...OK
Sending bytes...9 bytes written
end flag was received
time: 0.193245
full time: 0.206170
Closing serial port...OK
C:\Documents\work\region\testProject\build (master -> origin)
λ source.exe
Opening serial port...OK
Sending bytes...9 bytes written
end flag was received
time: 0.115640
full time: 0.204010
Closing serial port...OK
的一个:
not exists
答案 1 :(得分:4)
有时,最简单的解决方法是将其打开。您将如何找到所有已订购苹果的客户。那很简单...
SELECT cusomer_id
FROM customer_order co
INNER JOIN customer_order_line col
ON co.order_id = col.order_id
INNER JOIN product p
ON col.order_line_product_id = p.product_id
WHERE p.product_name = 'apple'
然后,这只是查找列表中NOT IN
的所有客户的情况
SELECT *
FROM customer
WHERE id NOT IN (
SELECT cusomer_id
FROM customer_order co
INNER JOIN customer_order_line col
ON co.order_id = col.order_id
INNER JOIN product p
ON col.order_line_product_id = p.product_id
WHERE p.product_name = 'apple'
)
还有很多其他(并且可能更有效)的方法来执行此操作,但是希望这可以使您走上正确的轨道。
答案 2 :(得分:4)
这是另一种方式:
select co.name, count(*)
from customer_order co
left join join customer_order_line col on co.order_id = col.order_id
left join product p on p.product_id = p.order_line_product_id
where p.product_name = 'Apple'
group by co.name
having count(*) = 0;