离开加入并从另一张桌子获得额外的

时间:2015-10-30 15:48:14

标签: database oracle join left-join inner-join

我有三个表,如下所示。我需要在Customer和Order表上进行左连接,这很好。在进行左连接之后,我需要每个客户的“城市”,并且“城市”值在ADDRESS表中。

客户

cus_id

订单

order_id
cus_id

ADDRESS

cus_id
city

下面的查询返回了13条记录,没有带有ADDRESS表的内连接

SELECT a.cus_id, 
       b.order_id
FROM   customer a 
       LEFT JOIN orders b 
              ON a.cus_id = b.cus_id

此查询在ADDRESS上使用内部联接返回了10个结果

SELECT a.cus_id, 
       b.order_id, 
       c.city 
FROM   customer a 
       LEFT JOIN orders b 
              ON a.cus_id = b.cus_id 
       INNER JOIN address c 
               ON c.cus_id = a_cus_id 

3条记录在哪里消失?

1 个答案:

答案 0 :(得分:1)

我做了一个数据样本 你能检查所有客户都有地址吗?

create table customer(cus_id int);
create table orders(order_id int, cus_id int);
create table address(cus_id int, city varchar2(50));

insert into customer(cus_id) (select rownum from all_objects where rownum < 14) 
insert into orders(order_id, cus_id) select cus_id, cus_id from customer;
insert into address(cus_id, city) select cus_id, cus_id||' city' from customer;


SELECT a.cus_id, 
       b.order_id, 
       c.city 
FROM   customer a 
       LEFT JOIN orders b 
              ON a.cus_id = b.cus_id 
       INNER JOIN address c 
               ON c.cus_id = a.cus_id;
--13 records               

update address
  set city = null
where cus_id >10                  

- 执行SELECT查询 - 它返回13条记​​录,但3条最后的记录具有空值

delete from address
  where cus_id >10

- 执行SELECT查询 - 它返回10条记录

- 检查所有客户是否有地址

select cus_id from customer
minus
select cus_id from address