此数据库具有一对多关系,其中父表Customers是客户列表,子表Orders是他们购买的东西的列表。我正在尝试开发一个查询来选择已经购买电视和沙发的客户。以下查询返回0结果。
SELECT Customer.*
FROM Customer
JOIN Orders
ON Customer.ID = Orders.customerID
WHERE Orders.item = 'television'
AND Orders.item = 'couch';
用OR替换AND并不起作用,因为它会返回已购买两件商品或只购买其中一件商品的客户。我的目标结果就是购买两者的客户。
答案 0 :(得分:2)
你需要利用你正在使用哪种sql风格的子查询(或联合)?
SELECT *
FROM CUSTOMER c
WHERE EXISTS (SELECT 1 FROM ORDERS o WHERE c.id = o.id and type = 'couch')
and EXISTS (SELECT 1 FROM ORDERS o WHERE c.id = o.id and type = 'tv')
答案 1 :(得分:1)
我不是MySQL用户,但我从中了解到很多查询都很慢。以下是仅需要单个子查询的选项。
SELECT *
FROM CUSTOMER c
WHERE (
SELECT COUNT(DISTINCT o.type) FROM ORDERS o
WHERE o.id = c.id AND o.type IN ('couch', 'tv')
) = 2
和
SELECT *
FROM CUSTOMER c
WHERE c.id IN (
SELECT o.id FROM ORDERS o
WHERE o.type IN ('couch', 'tv')
GROUP BY o.id
HAVING MIN(o.type) <> MAX(o.type) -- or COUNT(DISTINCT o.type) = 2
)