我有一个表名 tbl_marketing
包含许多列
DB_ID,db_customer,db_brand,db_client ....
另一个表名tbl_phonecall
包含许多列,并与tbl_marketing
中的db_mid
相关联,其中包含tbl_marketing
的 id
DB_ID,db_subject,db_due,db_nextdate,db_mid
知道我创建了一个搜索表单,这个搜索表单应该在tbl_marketing上的所有字段上搜索,并在用户进行搜索时在db_due和db_nextdate中搜索结果应该是这样的
客户品牌客户即将到期
来自tbl_marketing
的客户品牌和客户以及来自tbl_phonecall
对于该搜索,我使用此php
代码
$q = array();
$sql = "";
if(isset($_POST['txt_name']) && !empty($_POST['txt_name'])){
$name = mysqli_real_escape_string($conn,$_POST['txt_name']);
$q[] = "tbl_marketing.db_customer='".$name."' ";
}
if(isset($_POST['txt_client']) && !empty($_POST['txt_client'])){
$client = mysqli_real_escape_string($conn,$_POST['txt_client']);
$q[] = "tbl_marketing.db_client='".$client."' ";
}
if(isset($_POST['txt_brand']) && !empty($_POST['txt_brand'])){
$brand = mysqli_real_escape_string($conn,$_POST['txt_brand']);
$q[] = "tbl_marketing.db_brand='".$brand."' ";
}
if(isset($_POST['txt_dateofcalling']) && !empty($_POST['txt_dateofcalling'])){
$dateofcalling= mysqli_real_escape_string($conn,$_POST['txt_dateofcalling']);
$searchdateofcalling=date("Y-m-d H:i:s", strtotime($dateofcalling));
$q[] = "DATE(tbl_phonecall.db_due)='".$searchdateofcalling."' ";
}
if(isset($_POST['txt_nextdate']) && !empty($_POST['txt_nextdate'])){
$nextdate= mysqli_real_escape_string($conn,$_POST['txt_nextdate']);
$searchnextdate=date("Y-m-d H:i:s", strtotime($nextdate));
$q[] = "DATE(tbl_phonecall.db_nextdate)='".$searchnextdate."' ";
}
$first = true;
foreach($q as $qu){
if($first){
$sql .= " where ".$qu;
$first = false;
}else{
$sql .= " and ".$qu;
}
}
$query=mysqli_query($conn,"select tbl_marketing.*,tbl_phonecall.* from tbl_marketing,tbl_phonecall {$sql}")or die(mysqli_error($conn));
但此查询会重复值
我如何解决这个问题并得到像我之前发布的结果
答案 0 :(得分:0)
看起来你错过了加入条件
where tbl_marketing.db_id = tbl_phonecall.db_mid
如果您想要从tbl_phoneeting返回记录,即使tbl_phonecall表中不存在匹配的记录,请在查询中使用左连接
select tbl_marketing.*,tbl_phonecall.*
from tbl_marketing left join tbl_phonecall
on tbl_marketing.id = tbl_phonecall.mid
where ....<<where conditions here>>