首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

【】优化一段大量UNION 的语句

2012-12-25 
【在线等】优化一段大量UNION 的语句现在有一批从table A提取的id号(很不规则的,是客服手工提取的),要与tabl

【在线等】优化一段大量UNION 的语句
现在有一批从table A提取的id号(很不规则的,是客服手工提取的),要与table B做jion,但id号太多了,有10万之多
我用以下语句进行运行,爆慢无比
select aa.id ,bb.name from
(select 1 as id union all
select 1 as id union all
...
select 10000 as id ) as aa 
innet join table B as bb
on aa.id=bb.id


测试了下,主要问题出现在
select 1 as id union all
select 1 as id union all
...
select 10000 as id 这一段话上,求优化方法···
表说用in,那个更慢
[最优解释]
把union all 用临时表代替,然后join 试试,不行 就用exists
select id 
into #A
from (
select 1 as id union all
 select 1 as id union all
 ...
 select 10000 as id) as a


[其他解释]
將提取到的id保存到臨時表,并建索引,再join tb_B 進行查詢.

if object_id('tempdb..#tb_Collect')is not null
    drop table #tb_Collect
Go

select 1 as id Into #tb_Collect union all
select 1 as id union all
...
select 10000 as id

Create clustered index ix_#tb_Collect_id On #tb_Collect(id)

Select a.id,b.Name from #tb_Collect As a
    Inner join tb_B As b On a.id=b.id

[其他解释]
SELECT number FROM [master].dbo.spt_values sv WHERE sv.[type]='p' AND sv.number>0

[其他解释]
常量的IN
绝对要比你的语句要快
select id,name from B where B.id in(/*id们*/)

[其他解释]
10万个id自己手动写的?你真行
[其他解释]
樓主可以考慮把
elect 1 as id union all
select 1 as id union all
...
select 10000 as id

寫入一個table AA中,在table AA的id字段創建一個聚集索引,再與table B關聯。
select b.ID,b.Name From b where exists(select 1 from AA where ID=b.ID)

[其他解释]
引用:
常量的IN
绝对要比你的语句要快
SQL code?1select id,name from B where B.id in(/*id们*/)

大哥,测试过了,这种方法超慢,id太多
[其他解释]
引用:
引用:常量的IN
绝对要比你的语句要快
SQL code?1select id,name from B where B.id in(/*id们*/)
大哥,测试过了,这种方法超慢,id太多
呃!那表连接是最快的了
而你那搜索条件不是原本的表

而要重新建表或临时表的

我看算上建表的时间应该也快不到哪去吧
[其他解释]
你那堆union 是为了创建一个序列而已吧?如果是,那尝试使用select row_number() over(order by getdate())来产生一系列的ID。
[其他解释]
引用:

你那堆union 是为了创建一个序列而已吧?如果是,那尝试使用select row_number() over(order by getdate())来产生一系列的ID。
不是的,就是人工提取的id号··
[其他解释]
那收集的时候,你先放到一个临时表以后再用会比较合适。

热点排行