内联接在同一列上

时间:2013-05-10 12:50:05

标签: sql oracle

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

5 个答案:

答案 0 :(得分: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');

答案 1 :(得分: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

答案 2 :(得分: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子句中,因为它非常灵活。您可以非常轻松地为其他产品添加其他条件。

答案 3 :(得分: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')

答案 4 :(得分: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。

相关问题