当前位置:Gxlcms > PHP教程 > 有and有OR的依据几个字段生成SQL语句

有and有OR的依据几个字段生成SQL语句

时间:2021-07-01 10:21:17 帮助过:30人阅读

有and 有OR的根据几个字段生成SQL语句
有如下图的数据表信息,有什么好的方法把它们组合成一条SQL?如果全是and 的或者全是or的,这方法好办,可是两个同时都有的,怎么办呢?



全是AND 或OR的话

PHP code

        $sql = "select * from sk_cvfilter where cvid=58 and columnname!=''";
        $query = mysql_query($sql);
        $sql = '';
        while($row = mysql_fetch_assoc($query)){
            if($row['comparator']=='eq'){$comparator="=";}
            else{$comparator=$row['comparator'];}
            $sql .=$row['columnname'].$comparator."'".$row['value']."' ".$row['andor'].' ';
        }



------解决方案--------------------
SQL code
select * from sk_cvfilter where cvid=58 and columnname!='' and andor='and' or andor='or'

------解决方案--------------------
你的这个记录有问题,为什么呢?

例如出现一个 (a = 1 or (b=2 and b=3)),这个时候,你是怎么记录的?

我猜是这样的

columnname comparator value andor
a eq 1 or
b eq 2 and
c eq 3

这个时候问题出现了,假如你不知道上面的那个关系式(a = 1 or (b=2 and b=3)),
如果只从结构看的话,你是认为

(a = 1 or b =2 ) and b = 3

还是

a = 1 or (b=2 and b=3)

上述问题不考虑,所有or为一个条件和其他条件and的写法


PHP code

------解决方案--------------------
PHP code



                  

	 	
                    
                    
                    
                    
                    
                

人气教程排行