SQL 查询 select 具有同一列中具有不同值的子记录的父项

SQL Query to select parent that has child records with different values in the same column

此数据库具有一对多关系,其中父 table 客户是客户列表,子 table 订单是他们购买的物品列表.我正在尝试向 select 购买了电视和沙发的客户提出查询。以下查询返回 0 个结果。

SELECT Customer.*
FROM Customer
JOIN Orders
ON Customer.ID = Orders.customerID
WHERE Orders.item = 'television'
AND Orders.item = 'couch';

将 AND 替换为 OR 不起作用,因为它 returns 购买了两件商品或仅购买其中一件商品的客户。我的目标结果是同时购买了两者的客户。

您需要利用子查询(或联合)您使用的是哪种 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')

我不是 MySQL 用户,但我从 SO 中了解到许多查询可能很慢。以下是仅需要单个子查询的选项。

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
)