Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/2/3 6:41:46
两个小问题where 1=1 和 count(1) 与 count(-)_[SQL Server教程]

两个小问题where 1=1 和 count(1) 与 count(*)_[SQL Server教程]

where 1=1有什么用?在SQL语言中,写这么一句话就跟没写一样。


select * from table1 where 1=1与select * from table1完全没有区别,甚至还有其他许多写法,1<>2,'a'='a','a'<>'b',其目的就只有一个,where的条件为永真,得到的结果就是未加约束条件的。


在SQL注入时会用到这个,例如select * from table1 where name='lala'给强行加上select * from table1 where name='lala' or 1=1这就又变成了无约束的查询了。


最近发现的妙用在于,在不定数量查询条件情况下,1=1可以很方便的规范语句。例如一个查询可能有name,age,height,weight约束,也可能没有,那该如何处理呢?


String sql=select * from table1 where 1=1


为什么要写多余的1=1?马上就知道了。


if(!name.equals("")){
sql=sql+"name='"+name+"'";
}
if(!age.equals("")){
sql=sql+"age'"+age+"'";
}
if(!height.equals("")){
sql=sql+"height='"+height+"'";
}
if(!weight.equals("")){
sql=sql+"weight='"+weight+"'";
}


如果不写1=1呢,那么在每一个不为空的查询条件面前,都必须判断有没有where字句,否则要在第一个出现的地方加where


where 1=1的写法是为了检化程序中对条件的检测
打个比方有三个参数a, b, c
@sql=select * from tb'
这三个参数都可能为空
这时你要构造语句的话,一个个检测再写语句就麻烦
比如
if @a is not null
@sql=@sql + " where a=' + @a
if @b is not null
这里你怎么写?要不要加where 或直接用 and ?,你这里还要对@a是否为空进行检测


用上 where 1=1 之后,就不存在这样的问题, 条件是 and 就直接and ,是or就直接接 or


----------------------------------count(1) 与 count(*)



这个要看你自己数据库设计的结构啦
如果你的数据表没有主键,那么count(1)比count(*)快
如果有主键的话,那主键(联合主键)作为count的条件也比count(*)要快
如果你的表只有一个字段的话那count(*)就是最快的啦



count(*) count(1) 两者比较。主要还是要count(1)所相对应的数据字段。
如果count(1)是聚索引,id,那肯定是count(1)快。但是差的很小的。
因为count(*),自动会优化指定到那一个字段。所以没必要去count(?),用count(*),sql会帮你完成优化的.


来源:http://blog.csdn.net/lee576/archive/2006/11/06/1370361.aspx






If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759