【发布时间】:2014-09-27 15:10:57
【问题描述】:
我正在尝试将 EXISTS 中的查询重写为 JOIN 和反之亦然。
所以我有这个:
Oracle 11g R2 架构设置:
create table store
(
storeKey number,
storeName varchar2(500),
storeLocationKey number,
constraint StorePK primary key(storeKey)
);
create table storeLocation
(
storeLocationKey number,
storeLocationName varchar2(500),
storeCountry varchar2(500),
constraint StoreLocPK primary key(storeLocationKey)
);
insert into store values(1, 'Le Store', 1);
insert into store values(2, 'La tiendinha', 2);
insert into store values(3, 'The SuperHyperMegaStore', 3);
insert into store values(4, 'Le Other Store', 1);
insert into store values(5, 'La tienda', 4);
insert into store values(6, 'Chiquinha Tienda', 2);
insert into store values(7, 'Pecorela Tiendinha', 3);
insert into store values(8, 'Le Petit Store', 1);
insert into store values(9, 'Tienda Cipote', 4);
insert into store values(10, 'Tienda Desconocida', 0);
insert into storeLocation values(1, 'Camps Elisees', 'France');
insert into storeLocation values(2, 'Brasilia', 'Brasil');
insert into storeLocation values(3, 'Boston', 'USA');
insert into storeLocation values(4, 'San Salvador', 'El Salvador');
查询 1:
SELECT store.*
FROM store
LEFT OUTER JOIN storeLocation
ON store.storeLocationKey = storeLocation.storeLocationKey
WHERE storeLocation.storeCountry <> 'France'
ORDER BY store.storeKey ASC
| STOREKEY | STORENAME | STORELOCATIONKEY |
|----------|-------------------------|------------------|
| 2 | La tiendinha | 2 |
| 3 | The SuperHyperMegaStore | 3 |
| 5 | La tienda | 4 |
| 6 | Chiquinha Tienda | 2 |
| 7 | Pecorela Tiendinha | 3 |
| 9 | Tienda Cipote | 4 |
查询 2:
SELECT *
FROM store
WHERE EXISTS (
SELECT 1
FROM storeLocation
WHERE storeLocationKey = store.storeLocationKey
AND storeCountry <> 'France'
)
ORDER BY storeKey ASC
| STOREKEY | STORENAME | STORELOCATIONKEY |
|----------|-------------------------|------------------|
| 2 | La tiendinha | 2 |
| 3 | The SuperHyperMegaStore | 3 |
| 5 | La tienda | 4 |
| 6 | Chiquinha Tienda | 2 |
| 7 | Pecorela Tiendinha | 3 |
| 9 | Tienda Cipote | 4 |
查询 3:
-----------------------------
SELECT store.*
FROM store
LEFT OUTER JOIN storeLocation
ON store.storeLocationKey = storeLocation.storeLocationKey
where storeLocation.storeLocationName is null
ORDER BY store.storeKey ASC
| STOREKEY | STORENAME | STORELOCATIONKEY |
|----------|--------------------|------------------|
| 10 | Tienda Desconocida | 0 |
查询 4:
SELECT store.*
FROM store
WHERE NOT EXISTS (
SELECT NULL
FROM storeLocation
WHERE storeLocationKey = store.storeLocationKey
)
| STOREKEY | STORENAME | STORELOCATIONKEY |
|----------|--------------------|------------------|
| 10 | Tienda Desconocida | 0 |
从这里开始,我有几个(愚蠢的)问题:
为什么必须关联查询 2 和 4(当我没有关联查询时,它什么也没有返回)?存在/不存在是否必须与工作相关联?
在哪些情况下最好使用它们中的任何一个?
处理大量数据 (DW) 会有所不同吗?
谢谢。
【问题讨论】:
标签: database oracle left-join exists