2017-02-09 38 views
1

我有一個表名tbl_marketing包含許多列Mysql的搜索在兩個表

DB_ID,db_customer,db_brand,db_client ....

另一個表名tbl_phonecall包含許多列,並與鏈接tbl_marketingdb_mid這包含ID tbl_marketing

分貝 _id,db_subject,db_due,db_nextdate,db_mid

知道我創建一個搜索形成這種搜索形式應該做的所有字段中輸入搜索上tbl_marketing和db_due和db_nextdate在tbl_phonecall當用戶做他的搜索結果應該喜歡這個

客戶品牌客戶因nextdate 客戶對品牌和客戶從tbl_marketingtbl_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

echo($ sql)在選擇查詢和顯示內容之前? – affaz

+0

@affaz select tbl_marketing。*,tbl_phonecall。*來自tbl_marketing,tbl_phonecall其中DATE(tbl_phonecall.db_due)='2017-02-01 00:00:00' – m7md

+0

你在select之前還是之後給出echo? – affaz

回答

0

看起來像以前一樣,你已經錯過了加盟條件

where tbl_marketing.db_id = tbl_phonecall.db_mid 

萬一即使tbl_phonecall表中沒有匹配的記錄,您也想從tbl_marketing返回記錄,請在查詢中使用左連接

select tbl_marketing.*,tbl_phonecall.* 
from tbl_marketing left join tbl_phonecall 
on tbl_marketing.id = tbl_phonecall.mid 
where ....<<where conditions here>> 
+0

這隻工作,如果我搜索tbl_phonecal到期日和下一個日期,但如果我在tbl_marketing的字段上搜索沒有工作給我沒有結果 – m7md

+0

可能tbl_phonecal沒有記錄匹配該ID。使用左加入您的查詢 \t選擇tbl_marketing。*,tbl_phonecall。* \t從tbl_marketing左連接上tbl_marketing.id = tbl_phonecall.mid tbl_phonecall \t \t哪裏..​​.... <<這裏這裏條件>> – user7239725

+0

請編輯你的答案是正確的 – m7md