SQL - 如何在没有subselect的情况下排除结果?

时间:2011-09-13 02:28:09

标签: mysql sql

我坚持使用sql查询来列出购买产品但未购买产品的客户b。 这是我的表

表客户

id_customer   customer_name
1             name1
2             name2
3             name3

表格顺序

id_order   id_customer  product
1          1            a
2          1            b
3          2            b
4          3            a

我试试:

SELECT * FROM customer, order WHERE customer.id_customer = order.id_customer
AND (order.product='a' AND order.product<>'b')

SELECT * FROM customer, order WHERE customer.id_customer = order.id_customer
AND (order.product IN ('a') AND order.product NOT IN ('b'))
[AND (order.product = 'a' AND order.product <> 'b')]

SELECT table1.id_customer, table1.customer_name FROM customer INNER JOIN order ON customer.id_customer = order.id_customer
WHERE order.product IN ('a') AND order.product NOT IN ('b')
[WHERE order.product = 'a' AND order.product <> 'b']

但它没有正确答案,因为它返回:

1          1            a
4          3            a

答案应该是:

4          3            a

请任何人帮助我。非常感谢你

2 个答案:

答案 0 :(得分:3)

您可以使用联接来过滤客户是否拥有产品a,b中的每一个,然后查询联接以实现您的特定逻辑。它看起来像这样:

select distinct   -- pull only unique customer information
    C.*
from
    customer C
left join   -- orders of product a, which should exist
    order OA on OA.id_customer = C.id_customer and OA.product = 'a'
left join   -- orders of product b, which should not exist
    order OB on OB.id_customer = C.id_customer and OB.product = 'b'
where       -- orders of product a should exist
    OA.id_order is not null
and         -- orders of product b should not exist
    OB.id_order is null

答案 1 :(得分:0)

我认为我们没有所有细节,所以这里是一个使用子查询(忽略问题标题)并返回客户而不是订单(忽略预期结果集)的查询:

SELECT * 
  FROM customer AS c
 WHERE EXISTS (
               SELECT * 
                 FROM order AS o
                WHERE o.id_customer = c.id_customer  
                      AND product = 'a'
              )
       AND NOT EXISTS (
                       SELECT * 
                         FROM order AS o
                        WHERE o.id_customer = c.id_customer  
                              AND product = 'b'
                      );