---
title: "使用WITH提高查询效率"
author: "core_qq"
date: "2012-01-15T21:02:27Z"
tags: ["Oracle", "with"]
categories: ["数据库"]
slug: "with"
draft: false
lastmod: "2012-01-15T21:02:27Z"
id: 1347268
url: "https://core-qq.iteye.com/blog/1347268"
---

前两天的业务需求里需要关联好几张表出一个详单报表，这个需求其实很简单，但是数据量大，源表又不是分区表，就变得很头疼了。

     最初我的代码大概是这样子的：

```
select 
a.id,
a.name,
a.code,
b.type,
(
select p_name
from C c
where c.pid = b.pid
)
from A a, B b
where a.id = b.id and a.id > 1000;
```

     这样的话如果三个表数据量小就没事儿了，一会儿就跑出来了。但是我们的A表上亿，A一个id对应B里的好多个id，那么B的数据量就更大了。C也差不多，这样一来就要老命了。这个时候我想到了用with这个办法来减小数据量。

     WITH这个东西主要是产生一个临时的表，可以通过各种条件见小数据量，挑选需要的列，如此这般，数据量就会小很多。WITH没有办法提高效率，但是就是降低数据量，靠硬件的优势。修改以后的代码如下：

```
with AA as (select id, name, code, type from A where id > 1000),
BB as (select type, pid from B),
CC as (select p_name, pid from C)
select AA.id, AA.name, AA.code, BB.type, C.p_name
where AA.id = BB.id
and CC.pid = BB.pid;
```

     经过业务上跑了一遍，原本13个小时没有跑出来的过程，居然很快的跑出来了，我很欣慰。就在这里记录一下这个知识点，和大家分享。