我有一个包含有关某人信息的数据库。让我们说我想搜索一个国家的人。所以我输入美国并得到10个数据。在那之后,我想进一步缩小到男性。
如何执行首先搜索国家/地区的SQL,然后搜索性别。
$sql="SELECT * FROM people
WHERE country like $search1%
ORDER BY ASC ";
和
$sql="SELECT * FROM people
WHERE country like $search1%
AND Gender = $search2
ORDER BY ASC ";
如何将它们组合成一个$ sql语句?
答案 0 :(得分:1)
尝试将所有案例与此代码结合使用:
$sql = "SELECT *
FROM people
WHERE (country LIKE %$search1% AND $search2='')
OR ($search1='' AND gender=$search2)
OR (country LIKE %$search1% AND gender=$search2)";
添加您自己的ORDER BY
子句。
答案 1 :(得分:0)
更新
SELECT *
FROM people
WHERE
((country = ('USA') AND gender = 'male')
OR
(country LIKE ('USA') OR gender LIKE 'male'))
ORDER BY ASC
第一行((country = ('USA') AND gender = 'male')
两者兼而有之
第二行(country LIKE ('USA') OR gender LIKE 'male'))
将'%'
放入您不需要的地方。
例如(country LIKE ('USA') OR gender LIKE '%'))
答案 2 :(得分:0)
子查询:
SELECT * FROM(SELECT * FROM people WHERE country like $ search1%) as people1 WHERE Gender = $ search2 ORDER BY ASC
答案 3 :(得分:-1)
你可以结合这个。首先检查过滤器是否有值。
检查使用if条件并连接一个字符串然后执行它,就像一个。
$sql="SELECT * FROM people WHERE 1 ";
if($search1% != NULL){
$sql.="AND country like $search1% ";
}
elseif($search2 != NULL){
$sql.="AND Gender = $search2 ";
}
$sql.="ORDER BY ASC ";
答案 4 :(得分:-1)
有两种方式
在MySql中创建视图对于此类复杂查询
在php中编写一个函数来构建上面的查询
<?php
function searchQuery($key,$gender,$order){
$sql = "SELECT * FROM people WHERE country like %$key% AND Gender = $gender ORDER BY $order"
$query= mysql_query($sql);
while($data= mysql_fetch_array($query)) {
//Do your stuff here and collect in one variable say $searchData
}
return $searchData
}
希望这会对你有所帮助