---
title: "连接查询与子查询"
author: "zhouzhao21"
date: "2008-11-10T16:50:20Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-11-17T00:50:54Z"
id: 265140
url: "https://kyo-cc.iteye.com/blog/265140"
---

in oracle :
在一个查询中有许多条件相同的子查询，但需要的值不同。例如： 
SQL 1:

```sql


select 
     (select u.name from user u where u.id = i.id) as name,
     (select u.nick_name from user u where u.id = i.id) as nick_name,
     (select u.create_date from user u where u.id = i.id) as create_date,
     i.title as title,
     i.content as content
from info i 


```

这个 SQL 里面有三个子查询,并且是同样的查询条件,应该能够进行优化.

也可以改为连接查询:
SQL 2:

```sql


select 
     u.name as name,
     u.nick_name as nick_name,
     u.create_date as create_date,
     i.title as title,
     i.content as content
from info i join user u on i.id = u.id 


```


有两个问题要请教大家:
1. SQL 1 的子查询明显可以优化, 问题是怎么将子 SQL 提出来,做为一个对象使用,就像连接查询中 u.name , u.nick_name... 这样使用, 知道的一个办法就是使用连接查询,还有没有其他的办法,比如使用 pl/sql. 
2. SQL 2 的连接查询,如果 user 表中有太多的字段和若干索引,会不会将 user 表中的所和索引都检索一遍, 从而大大影响了效率?
请大家基于 oracle 9i 以上版本进行讨论.


关于这两个查询有篇不错的文章：
<http://hi.baidu.com/round_365/blog/item/4bdf1e23f00f304d9258078d.html>