Heim  >  Artikel  >  Backend-Entwicklung  >  sql多条件查询

sql多条件查询

WBOY
WBOYOriginal
2016-10-17 09:30:081270Durchsuche

要实现多条件查询 其中值为0时为不限条件 怎么用sql实现

例如:查询某地区某类型商铺 有可能地区为不限 类型为中餐 查询时就不需要where 地区=值,而是只有where 类型=中餐,选择地区为北京 类型为中餐 查询时就是where 地区=北京 AND 类型=中餐。

然后还有很多其他条件,在后端用if else判断之后再用不同的sql语句查询的话太繁琐了,不太了解sql但我觉得sql应该有相应的解决方案,求教。

回复内容:

要实现多条件查询 其中值为0时为不限条件 怎么用sql实现

例如:查询某地区某类型商铺 有可能地区为不限 类型为中餐 查询时就不需要where 地区=值,而是只有where 类型=中餐,选择地区为北京 类型为中餐 查询时就是where 地区=北京 AND 类型=中餐。

然后还有很多其他条件,在后端用if else判断之后再用不同的sql语句查询的话太繁琐了,不太了解sql但我觉得sql应该有相应的解决方案,求教。

你可以if判断了以后在拼入相应的where
ex: $sql = select * from xxx where 1=1;

<code>if(类型!=0){
    $sql .= 'and where 类型 = 中餐';
}</code>

把查询的条件作为一个Map params; 然后用一个方法进行额外查询语句的拼接;

<code>public String getWhere(Map<string object> params) {
    String str = "";
    
    if(params.size() > 0) {
        boolean and = false;
        for(String param : params.keySet()) {
            Object value = params.get(param);
            if(value == null || value.equals(0)) {
                continue;
            } else {
                if(and) {
                    str = str + " and " + param + " = " + " " + value;
                } else {
                    and = true;
                    str = str + param + " = " + " " + value;
                }
                
            }
        }
    }
    
    if(str != "") { 
        str = " where " + str;
    }
    
    return str;
}</string></code>

mybatis拼SQL
JPA拼creteria

链接条件 and or

查询Mysql是使用字符串来传递Mysql查询命令的,所以要修改where后面的查询条件是完全可行的,可以先建立一个存储这些命令的字符串数组,在用户每次修改条件,例如勾选了地址,就修改数组的相应值,或者在点击查询后,检查界面中那些组件,例如餐类或者地址被勾选了,就获取他们的值,添加到数组中,然后在开始查询是遍历他们,为空的就不做处理,不为空的就添加到统一条件字符串里,最后添加到查询语命令字符串中就可以啦
string cmd = “select * from 表名 where 统一条件”
新手一只,考虑可能不周,不过这中做法应该没什么大问题哈

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn