0
Customer  Table
----------------------
CustomerName
Peter
Sam


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

预期结果

Customer
Sam

我想要结果作为购买“衣服”而不是“手机”的客户,我试过了

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
4

5 回答 5

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');
于 2013-05-10T12:54:36.830 回答
1

您可以使用 OracleMINUS运算符使其变得简单;

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;

一个用于测试两者的 SQLfiddle

于 2013-05-10T12:58:33.167 回答
1

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

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子句中,因为它非常灵活。您可以很容易地为其他产品添加附加条件。

于 2013-05-10T13:14:55.340 回答
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')
于 2013-05-10T12:53:48.500 回答
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'

我希望能帮助你。拥抱,文。

于 2013-05-10T13:07:42.133 回答