分享

SQL语句中的 where 1=1

 冬瓜小屋 2015-05-25

就是条件永远为真,查出所有数据来

在组合查询条件时候多用:

String sql="select * from user where 1=1 ";

if(username!=null) sql=sql+ " and username='"+username+"'";

if(password!=null) sql=sql+ " and password='"+password+"'";

这样方便很多,及时username,password两者都为空都可以查询

永远为真

主要是为了便于动态连接后续条件

有时候想查看一下表的字段就
select * from UB where 1=2,表示false 1=1表示true

-------------------------------------------

package StringTest;

public class Where {

    /**
     * 我用于高级查询情况下
     *
@param args
    
*/
    public static void main(String[] args) {
        Where s= new Where();
        s.print("13432134321", "www.cjfuture.cn");
        //null时,即为用户没有写值
        s.print(null, "www.cjfuture.cn");
    }
    public void print(String mobile,String url){
        StringBuffer sb = new StringBuffer("select id from tab where 1 = 1 ");
        //如果没有1=1,下面的判断语句会比现在写复杂
        if(mobile!=null){
            sb.append("and mobile = "+mobile);
        }
        if(url!=null){
            sb.append("and name = "+url);
        }
        System.out.println(sb.toString());
    }
   
    public void otherPrint(String mobile,String url){
        StringBuffer sb = new StringBuffer("select id from tab");
        //如果没有1=1,下面的判断语句会比现在写复杂,where放在哪里合适?
        if(mobile!=null){
            sb.append("and mobile = "+mobile);
        }else{
            sb.append("");        //如何写?
        }
        if(url!=null){
            sb.append("and name = "+url);
        }else{
            sb.append("");        //如何写?
        }
        System.out.println(sb.toString());
    }
}

*******************************************************************

[转]sql语句中where 1=1的作用
2008-08-27 09:22
where 1=1
最近看到很多sql里用到where 1=1,原来觉得这没用嘛,但是又想到如果没用为什么要写呢?于是在网上

查了查,在这里就浅谈一下:
1=1 永真, 1<>1 永假。

1<>1 的用处:
用于只取结构不取数据的场合
例如:
create table table_temp tablespace tbs_temp as
select * from table_ori where 1<>1
建成一个与table_ori 结构相同的表table_temp,但是不要table_ori 里的数据。(除了表结构,其它结

构也同理)

1=1的用处
用于动态SQL
例如 lv_string := 'select tbl_name,tbl_desc from tbl_test where 1=1 '||l_condition;
当用户选择了查询的名称'abc'时l_condition :='and tbl_name = ''abc'''';但是当用户没有

选择名称查询时l_condition就为空 这样 lv_string = 'select tbl_name,tbl_desc from tbl_test

where 1=1 ' ,运行也不会出错,相当于没有限制名称条件。但是如果没有1=1的条件,则lv_string =

'select tbl_name,tbl_desc from tbl_test where ';这样就会报错。

除了1=1 或1<>1之外的其它永真永假的条件同理。

来源:http://hi.baidu.com/jzg7366/blog/item/e59dbaec8d33a5d42e2e210a.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多