[SQL]SQL小技巧两则

由于近期我家网络及工作关系,又有好久没有维护blog了,今天添两个sql小技巧:

一:SQL 复合条件搜索
相信大家都有过在程序里生成多个条件查询的sql语句,比如:
select   *   from  employees  where  title = ' 经理‘and name= ' 张三 '’

这样生成多个条件的代码可能是这样
             // 这个地方获得许多条件......
             string  name  =  GetEmployeeNameTerm();
            
string  title  =  GetEmployeeTitleTerm();
            
// ........

            
string  sql  =   " select * from employee " ;
            
string   where   =   string .Empty;

            
if ( name  !=   string .Empty )
            
{
                
ifwhere == string.Empty )
                
{
                    
where += " where name = '" + name + "";
                }

            }

            
// 这个地方会和条件一样多......
             if ( title  !=   string .Empty )
            
{
                
//这个判断会重复很多次
                ifwhere == string.Empty )
                
{
                    
where += " where title = '" + title + "";
                }

                
else
                
{
                    
where += " and title = '" + title + "";
                }

            }

            
// ........

            
// 生成sql语句
            sql  +=   where ;

这里我们把上面的代码的写法换一下
             // 这个地方获得许多条件......
             string  name  =  GetEmployeeNameTerm();
            
string  title  =  GetEmployeeTitleTerm();
            
// ........

            
string  sql  =   " select * from employee " ;
            
// 注意,这里是7个字符
             string   where   =   "  where  " ;

            
if ( name  !=   string .Empty )
            
{
                
//注意,and后面有4个空格,与原始的where一样多
                where += " name = '" + name + "' and    ";
            }

            
// 这个地方会和条件一样多......
             if ( title  !=   string .Empty )
            
{
                
//省去N多判断
                where += " title = '" + title + "' and    ";
            }

            
// ........

            
// 生成sql语句
            sql  +=   where .Substring(  0 where .Length  -   7  );

这样可以省去许多条件判断语句(少打很多字母呢),而且逻辑更清晰

二、读取数据库中是否至少含有N条记录:
刚刚做的一个项目,数据库中有上百万条数据,做一个列出数据的查询少说2、3秒,多说5、6秒。而且做分页的时候count一下也需要很长时间。由于是web应用,所以这样的性能是不能忍受的。可是分页并不一定要知道一定有多少条记录,只要知道够不够一定条数的记录就可以了。比如说每页显示20条数据,显示10个页码,如果10页之后还有数据就显示各更多之类,点击之后显示后面的页码(如google的分页)。这样只要知道数据库中的数据是不是够 201条就可以了(取是否够201条的目的是如果多于200条就显示更多,不管多几条)。可以sql server 里的top关键字实现这样的功能:

select   count ( * from  (  select   top   201  orderID  from  orders )  as  tmpTable
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值