ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

关于SQL中的 where 1 = 1 的用法

2019-12-19 20:55:16  阅读:283  来源: 互联网

标签:commandText color 用法 whereClause SQL sqlStatement where


  在项目中的常见的一个操作:在有关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 ";
            sqlStatement += "year="+modelYear;
        }
        if (manufacturer != "")
        {
            if (whereClause != "")
                whereClause = whereClause + " and ";
            sqlStatement += "value="+manufacturer
        }
        if (color != "")
        {
            if (whereClause != "")
                whereClause = whereClause + " and ";
            sqlStatement += "color="+color
        }
        if (california)
        {
            if (whereClause != "")
                whereClause = whereClause + " and ";
            sqlStatement += "hasCatalytic=1"
        }

        if (whereClause != "")
            sqlStatement = commandText + "WHERE "+whereClause;

 

 加上where 1 = 1 后:

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

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

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

标签:commandText,color,用法,whereClause,SQL,sqlStatement,where
来源: https://www.cnblogs.com/wangkundentisy/p/12070032.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有