zoukankan      html  css  js  c++  java
  • 关于SQL中的 where 1 = 1 的用法

      在项目中的常见的一个操作:在有关SQL的代码中加入where 1 = 1,关于它的用法,可以总结如下:

      首先,where 1 = 1的用法往往是为了方便后续的给SQL增加where限制条件。如果实现加入了where 1 = 1,后续的条件只需加入and ...  这种形式的代码就可以准确执行了。举个例子,

    不加where 1 = 1 时:

           sqlStatement = "select * from table_car"
            whereClause = "";
            if (modelYear != 0)
            {
                if (whereClause != "")
                    whereClause = whereClause + " and ";
                whereClause += "year="+modelYear;
            }
            if (manufacturer != "")
            {
                if (whereClause != "")
                    whereClause = whereClause + " and ";
                whereClause += "value="+manufacturer
            }
            if (color != "")
            {
                if (whereClause != "")
                    whereClause = whereClause + " and ";
                whereClause += "color="+color
            }
            if (california)
            {
                if (whereClause != "")
                    whereClause = whereClause + " and ";
                whereClause += "hasCatalytic=1"
            }
    
            if (whereClause != "")
                sqlStatement = sqlStatement + "WHERE "+whereClause;
    

     加上where 1 = 1 后:

            sqlStatement = "select * from table_car where 1 = 1";
            if(Year != 0)
              sqlStatement +=" and year=" + modelYear
            if(manufacturer != "")
              sqlStatement += " and value=" + manufacturer
            if(color != "")
              sqlStatement += " and color=" + color
            if(california != 0)
              sqlStatement += " and hasCatalytic=1"
    

     很明显,加上where 1 = 1后,代码的拓展性大大增加而且更加简洁。在后续为SQL加入限制条件时会非常的方便。

    此外,SQL查询引擎在执行SQL时,如果遇到where 1 = 1 它会忽略这个条件,因此where 1 = 1 对SQL的性能并没有影响。

  • 相关阅读:
    PHPxiao程序用户登录页面,嘿嘿,模仿滴
    IE、 FireFox 的 javascript 日历控件
    经典推荐的 Smarty模板 教程
    推荐兼容 IE、 FireFox 的 javascript 日历控件
    最新php100视频教程的解压密码(截止83课时)
    上下左右 无缝隙 滚动代码
    ThinkPHP学习笔记一
    dedecms代码解密1:index.php简单分析
    40条技巧优化php代码
    导出excel小结(C#,.NET,Wpf)
  • 原文地址:https://www.cnblogs.com/wangkundentisy/p/12070032.html
Copyright © 2011-2022 走看看