我有一个搜索表单,用户可以输入任何字母单词并进行搜索
这个搜索在两个表中
表1是tbl_project
此表包含
db_projectname db_location db_client
xxxx vvv ccc
dddd ggg tttt
tbl_activities包含
db_projectname db_cost db_name
xxxx 500 ttt
xxxx 500 hhh
dddd 200 llll
我使用这个PHP代码进行搜索
$sq = "";
$qq=array();
if(isset($_POST['search']) && !empty($_POST['search'])){
$search = mysqli_real_escape_string($conn,$_POST['search']);
$qq[] = "tbl_project.db_projectname like '%".$search."%' ";
$qq[] = "tbl_project.db_location like '%".$search."%' ";
$qq[] = "tbl_project.db_client like '%".$search."%' ";
$qq[] = "tbl_project.db_offer like '%".$search."%' ";
$qq[] = "tbl_project.db_sheet like '%".$search."%' ";
$qq[] = "tbl_project.db_invoice like '%".$search."%' ";
$qq[] = "tbl_project.db_po like '%".$search."%' ";
$qq[] = "tbl_project.db_id like '%".$search."%' ";
}
$second=true;
foreach($qq as $que){
if($second){
$sq .= " where ".$que;
$second = false;
}else{
$sq .= " or ".$que;
}}
如果用户输入x或v或c或xxxx或vvv或ccc
,结果应如下所示xxxx 1000 vvv cccc
查询应如何获得此结果我已尝试不同的查询但我没有收到此结果
SELECT tbl_project.*
, (SELECT sum(tbl_activities.db_totalcost) AS total_cost FROM tbl_activities {$sq}
FROM tbl_project
答案 0 :(得分:0)
尝试这种方法:
$cond = "";
if(isset($_POST['search']) && !empty($_POST['search'])){
$search = mysqli_real_escape_string($conn,$_POST['search']);
$cond .= " and pa.db_projectname like '%".$search."%' ";
$cond .= " and pa.db_location like '%".$search."%' ";
$cond .= " and pa.db_client like '%".$search."%' ";
$cond .= " and pa.db_offer like '%".$search."%' ";
$cond .= " and pa.db_sheet like '%".$search."%' ";
$cond .= " and pa.db_invoice like '%".$search."%' ";
$cond .= " and pa.db_po like '%".$search."%' ";
$cond .= " and pa.db_id like '%".$search."%' ";
}
查询将是:
select p.*,sum(pa.db_totalcost) from tbl_project p left join
tbl_activities pa on p.db_projectname=pa.db_projectname
where 1 $cond group by p.db_projectname
答案 1 :(得分:0)
我想你想要这样的东西:
SELECT p.db_projectname, IFNULL(a.total, 0) as total, p.db_location, p.db_client FROM tbl_project as p
LEFT JOIN (select db_projectname, sum(db_cost) as total from tbl_activities group by db_projectname) as a
ON p.db_projectname = a.db_projectname