php中where1的用法,关于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 ";

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的性能并没有影响。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值