2013-05-10 25 views
0
Customer Table 
---------------------- 
CustomerName 
Peter 
Sam 


Sales Table 
----------------------- 
ProductName Customer 
Cloth   Peter 
Mobile   Peter 
Cloth   Sam 
Laptop   Sam 

预期结果内同一列加入

Customer 
Sam 

我想导致的客户谁buyed“布”,但不是“移动”,我想

select c.CustomerName from Customer c inner join Sales s1 on (s1.customer = c.customername and s1.productname = 'Cloth') inner join Sales s2 on (s2.customer = c.customername and s2.productname != 'Mobile'); 

但它总是返回两个条目

Customer 
Peter 
Sam 
Sam 

回答

0

试试这个:

select c.CustomerName 
from Customer c 
where exists(select 1 from sales s1 where s1.customer = c.customername and s1.productname = 'Cloth') 
and not exists (select 1 from sales s2 where s2.customer = c.customername and s2.productname = 'Mobile') 
2

相关的子查询会更好,因为您对购买多次布料的客户不感兴趣。

select 
    c.CustomerName 
from 
    Customer c 
where 
    exists (
    select null 
    from sales 
    where sales.customer = c.customername and 
      s1.productname = 'Cloth') and 
    not exists (
    select null 
    from sales 
    where sales.customer = c.customername and 
      s1.productname = 'Mobile'); 
+0

谢谢@David是不可能与innerjoins? – BreakHead 2013-05-10 12:59:32

+0

您必须将外部联接销售给“移动”才能找到销售,然后从结果中除去找到记录的结果以及“布料”的内部联接,然后删除结果集。它根本不会有效。 – 2013-05-10 13:03:52

1

您可以使用Oracle MINUS运算符来简化它;

SELECT "Customer" FROM SalesTable WHERE "ProductName"='Cloth' 
MINUS 
SELECT "Customer" FROM SalesTable WHERE "ProductName"='Mobile' 

另一个稍微复杂的选项是LEFT JOIN;

SELECT DISTINCT s1."Customer" 
FROM SalesTable s1 
LEFT JOIN SalesTable s2 
ON s1."Customer" = s2."Customer" 
    AND s2."ProductName" = 'Mobile' 
WHERE s1."ProductName" = 'Cloth' 
    AND s2."Customer" IS NULL; 

An SQLfiddle to test both with

0

首先你应该检查你的数据库模式。
如果没有ID,你永远不会做内部连接。 尝试使用关系创建表格。就像这样:

create table customer 
(
id_customer  int not null, 
ds_customername varchar(80) null, 
primary key (id_customer) 
) 

create table products 
(
id_product int not null, 
ds_product varchar(100) null, 
primary key (id_product) 
) 

create table sales 
(
id_sales int not null, 
id_product int not null, 
id_customer int not null, 
foreign key (id_product) references products (id_product), 
foreign key (id_customer) references customer (id_customer) 
) 

select customer.ds_customername 
from customer 
     inner join sales (customer.id_customer = sales.id_customer) 
     inner join products (products.id_product = sales.id_product) 
where products.ds_product = 'Cloth' 

好吧, 如果你不能做到这一点,你可以做你的查询(以旧的方式)是:

select Customer.customername 
    from  Customer 
      inner join on (customer.customername = sales.customer) 
    where sales.productname = 'Cloth' 

我希望帮你。 拥抱, Vin。

1

这是“set-set-set”查询的示例。我认为一个好的方法是使用聚合:

select s.Customer 
from Sales s 
group by s.Customer 
having sum(case when s.ProductName = 'Cloth' then 1 else 0 end) > 0 and -- has cloth 
     sum(case when s.ProductName = 'Mobile' then 1 else 0 end) = 0  -- does not have mobile 

我更喜欢把逻辑having子句中,因为它是非常灵活。您可以很容易地为其他产品添加附加条件。