oracle中的外部联接帮助

时间:2011-03-24 21:43:12

标签: oracle

我有:

select title, order#, STATE
from customers C, ORDERITEMS O, books b
where b.ISBN=O.ISBN (+)
order by title

但是我试图理解为什么没有订单#的行有状态

BODYBUILD IN 10 MINUTES A DAY   1003    CA
BODYBUILD IN 10 MINUTES A DAY   1003    WY
BODYBUILD IN 10 MINUTES A DAY   1003    TX
BODYBUILD IN 10 MINUTES A DAY   1003    NY
BODYBUILD IN 10 MINUTES A DAY   1003    WA
BODYBUILD IN 10 MINUTES A DAY   1003    ID
BODYBUILD IN 10 MINUTES A DAY   1003    FL
BUILDING A CAR WITH TOOTHPICKS  -   FL
BUILDING A CAR WITH TOOTHPICKS  -   NJ
BUILDING A CAR WITH TOOTHPICKS  -   GA
BUILDING A CAR WITH TOOTHPICKS  -   MI

2 个答案:

答案 0 :(得分:4)

如果在进行外连接时涉及多个表,我发现使用ANSI连接要容易得多:

SELECT title, order#, STATE
FROM customers c 
   JOIN orderitems O ON o.customer_id = c.id
   LEFT JOIN books b ON b.isbn = o.isbn
ORDER BY title

(这与Arjan发布的查询基本相同,只是标准语法)

根据您的需要,您可能还想对订购项目使用LEFT JOIN,例如如果您还想要没有订购项目的客户

也可以在选择列表中为列使用表别名。这样做会使语句更容易理解(因为您可以立即知道哪个列来自哪个表),并且它对更改更加稳定。

答案 1 :(得分:3)

您正在使用3个表,但只有一个表。这会让你得到太多结果。您将需要两个连接:可能以某种方式表客户也需要与OrderItems连接。

类似的东西:

and o.customerId = c.id

因此:

select b.title, o.order#, c.state
from customers c, orderitems o, books b
where o.customerId = c.id
and b.isbn = o.isbn (+)
order by title