易截截图软件、单文件、免安装、纯绿色、仅160KB

sql里的exists与in、not exists与not in的区别

系统要求进行SQL优化,对效率比较低的SQL进行优化,使其运行效率更高,其中要求对SQL中的部分in/not in修改为exists/not exists
修改方法如下:
in的SQL语句
SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime
from tab_oa_pub WHERE is_check=1 and
category_id in (select id from tab_oa_pub_cate where no='1')
order by begintime desc
修改为exists的SQL语句
SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime
from tab_oa_pub WHERE is_check=1 and
exists (select id from tab_oa_pub_cate where tab_oa_pub.category_id=convert(int,no) and no='1')
order by begintime desc
分析一下exists真的就比in的效率高吗?
    我们先讨论IN和EXISTS。
    select * from t1 where x in ( select y from t2 )
    事实上可以理解为:
    select *
      from t1, ( select distinct y from t2 ) t2
     where t1.x = t2.y;
    ——如果你有一定的SQL优化经验,从这句很自然的可以想到t2绝对不能是个大表,因为需要对t2进行全表的“唯一排序”,如果t2很大这个排序的性能是不可忍受的。但是t1可以很大,为什么呢?最通俗的理解就是因为t1.x=t2.y可以走索引。但这并不是一个很好的解释。试想,如果t1.x和t2.y 都有索引,我们知道索引是种有序的结构,因此t1和t2之间最佳的方案是走merge join。另外,如果t2.y上有索引,对t2的排序性能也有很大提高。
    select * from t1 where exists ( select null from t2 where y = x )
    可以理解为:
    for x in ( select * from t1 )
    loop
       if ( exists ( select null from t2 where y = x.x )
       then
          OUTPUT THE RECORD!
       end if
    end loop
    ——这个更容易理解,t1永远是个表扫描!因此t1绝对不能是个大表,而t


相关文档:

sql 2005 存储过程分页 java 代码

 create PROCEDURE pagelist
@tablename nvarchar(50),
@fieldname nvarchar(50)='*',         
@pagesize int output,--每页显示记录条数
@currentpage int output,--第几页
@orderid nvarchar(50),--主键排序
@sort int,--排序方式,1表示升序,0表示降序排列 ......

SQL语句优化方法

我们要做到不但会写SQL,还要做到写出性能优良的SQL语句。

(1)选择最有效率的表名顺序(只在基于规则的优化器中有效):

Oracle的解析器按照从右到左的顺序处理from子句中的表名,from子句中写在最后的表(基础表 driving table)将被最先处理,在f ......

多条件查询存储过程 SQL Server


多条件查询存储过程
 多条件查询存储过程 例一
create proc pr_select_Natural
(
 @CDATE  datetime,
 @FAC_NAME varchar(50),
 @BATTERY_TYPE varchar(20),
 @MAKE_MODE varchar(20),
 @PRODUCE_MODE varchar(20),
 @YEAR  char(4),
 @MONTH  char(2 ......

SQl 语句(常见) 新建,删除,修改表结构

新建表:
create table [表名]
(
[自动编号字段] int IDENTITY (1,1) PRIMARY KEY ,
[字段1] nVarChar(50) default '默认值' null ,
[字段2] ntext null ,
[字段3] datetime,
[字段4] money null ,
[字段5] int default 0,
[字段6] Decimal (12,4) default 0,
[字段7] image null ,
)
删除表:
Drop table [表 ......

修改SQL SERVER数据库表结构的SQL命令

  向表中增加一个 varchar 列:
  ALTER TABLE distributors ADD COLUMN address varchar(30);
  从表中删除一个字段:
  ALTER TABLE distributors DROP COLUMN address RESTRICT;
  在一个操作中修改两个现有字段的类型:
  ALTER TABLE distributors
  ALTER COLUMN address TYPE varchar(80),
......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号