多个加入同一个表 - Oracle

时间:2013-05-03 08:57:57

标签: sql oracle

enter image description here

我尝试了以下查询

SELECT Customer.*,
       ElectrnicItem.Product1 AS ElectronicItem1,
       ElectrnicItem.Product2 AS ElectronicItem2,
       ElectrnicItem.Product3 AS ElectronicItem3,
       ApparelItem.Product1 AS ApparelItem1,
       ApparelItem.Product2 AS ApparelItem2,
       ApparelItem.Product3 AS ApparelItem3
FROM Customer
LEFT JOIN Inventory AS ElectrnicItem 
ON (Customer.CustomerID = ElectrnicItem.CustomerID)
LEFT JOIN Inventory AS ApparelItem 
ON (Customer.CustomerID = ApparelItem.CustomerID)

但它总是返回:

  

ORA-00918列模糊定义

4 个答案:

答案 0 :(得分:0)

您缺少任何谓词,以将库中的行标识为“电子”或“服饰”。不确定那是不是修复。

答案 1 :(得分:0)

这个怎么样?

SELECT a.customer_id, a.customer_name, b.product1 electronicitem1,
       b.product2 electronicitem2, b.product3 electronicitem3,
       c.product1 apparelitem1, c.product2 apparelitem2,
       c.product3 apparelitem3
 FROM customer a, inventory b, inventory c
WHERE a.customer_id = b.customer_id(+)
  AND b.product_type(+) = 'Electronic'
  AND a.customer_id = c.customer_id(+)
  AND c.product_type(+) = 'Apparel';

答案 2 :(得分:0)

我创建了表Customer和Inventory,还插入了您提供的值。以下是查询:

select customer.*,ElectrnicItem.Product1 as ElectronicItem1,
ElectrnicItem.Product2  as ElectronicItem2,
ElectrnicItem.Product3 as ElectronicItem3,
ApparelItem.Product1 as ApparelItem1,
ApparelItem.Product2 as ApparelItem2,
ApparelItem.Product3 as ApparelItem3 
from customer 
left join inventory as ElectrnicItem on 
(customer.CustomerID = ElectrnicItem.CustomerID ) 
left join inventory as ApparelItem 
on (customer.CustomerID = ApparelItem.CustomerID )

它工作正常并给出以下结果:

    1   David Miller    mobile  headphone   trimmer mobile  headphone   trimmer
    2   Johnson         jeans   tshirt      NULL   jeans    tshirt      NULL               
    3   Diggs           NULL    NULL        NULL    NULL    NULL        NULL            

您提到的预期输出将永远无法实现。由于Customer表包含CustomerIdCustomerNameCustomer.*将检索CustomerIdCustomerName。因此CustomerName列不能包含任何NULL 值。

答案 3 :(得分:0)

好的,有点晚了,但...... 您不使用AS来为Oracle中的表设置别名,只使用别名列。尝试从表别名中删除所有AS:

SELECT Customer.*,
       ElectrnicItem.Product1 AS ElectronicItem1,
       ElectrnicItem.Product2 AS ElectronicItem2,
       ElectrnicItem.Product3 AS ElectronicItem3,
       ApparelItem.Product1 AS ApparelItem1,
       ApparelItem.Product2 AS ApparelItem2,
       ApparelItem.Product3 AS ApparelItem3
FROM Customer
LEFT JOIN Inventory ElectrnicItem 
ON (Customer.CustomerID = ElectrnicItem.CustomerID)
LEFT JOIN Inventory ApparelItem 
ON (Customer.CustomerID = ApparelItem.CustomerID)