欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

多条件查询_MySQL

程序员文章站 2022-06-08 09:35:32
...
有关多条件查询的问题,以前我在论坛发过帖子,前几天有网友对此感兴趣,我就花了点时间整理了一下,其实并没有什么特别的,关键在于写出正确的SQL查询语句,由于各人所用数据库不同,而SQL语句是相同的。所以在此我仅给出根据多个条件自动生成的符合要求的SQL语句。对条件的数目基本没有限制,不超过数组的组元数目就可以了。
说白了,其实就是字符串的游戏。拼拼凑凑而已。这里使用数组储存条件和查询语句,程序也不长,有详细的注释,不会化您多少功夫的。呵呵。
在conditions_search.html中输入您的查询条件,点击查询。您输入的条件在提交到display_search_SQL.php进行处理后,将给出合适的SQL语句。


/***************conditions_search.html****************/


Conditions_Search多条件查询


Conditions_Search多条件查询:

Condition1:

Condition2:

Condition3:

Condition4:





/***************conditions_search.html**********************/


/***************display_search_SQL.php*********************/
//从conditions_search.html接收到四个条件,
//condition1,condition2,condition3,condition4。
//其中有文本框输入的字符串,有列表框下拉选择的,
//这些接收条件的方式都不重要。
//条件还可以增加(没什么限制,当然也不要太大,超过数组的上限)。
//以下有几点注意:
//认为条件值为空时,不限制;
//要查询的表名为testtable;
//condition1对应的字段名为column1……
//

$ConditionsNumber=4; //共有4个条件。(可改为实际使用的条件数)
$ConditionsArray=array("$condition1","$condition2","$condition3","$condition4");
//把各个条件排入一个数组中,方便下面循环。(数组很容易扩充)
$SearchSQLArray=array(" where column1='$condition1'"," where column2 like '%$condition2%'"," where column3='$condition3'"," where column4='$condition4'");
//预写好一些SQL语句,下面再根据情况处理。(数组很容易扩充)

for($i=0;$i{
if($ConditionsArray[$i]=="")
$SearchSQLArray[$i]="";
//第一步处理:如果条件值为空,相应的SQL语句为空。
$haveWhere=false; //设“存在where”检查标志的初值为false。
for($j=0;$j//从开始到目前循环的i,处理有哪些where
//需要变为and。
{
$wherePosition=strpos($SearchSQLArray[$j],"where");
//检查i前面是否有where出现。
if(($wherePosition=="1")&&($haveWhere==false))
{
$SearchSQLArray[$i]=ereg_replace("where","and",$SearchSQLArray[$i]);
//where的位置为1,且前面已有where。
//则where换成and。
$haveWhere=true; //"存在where”检查标志设为true。
}
}
};

for($i=0;$i$sql=$sql.$SearchSQLArray[$i];
$sql="select * from mytable".$sql.";";
//组成SQL语句
echo $sql;
?>
/**************display_search_SQL.php*********************/


摘自:PHP中文用户