2012-03-29 115 views
0

我有這樣的代碼:PHP,通過關鍵字搜索的MySQL從多個表

function search_keyword(){ 
     $keyword = trim($_POST['keyword']); 
     $search_explode = explode(" ", $keyword); 
     $x = 0; 

     $sql = " (SELECT name AS type FROM global_info WHERE "; 
     foreach($search_explode as $each){ 
      $x++; 
      if($x == 1){ 
       $sql .= " name LIKE '%$each%'";}       
      else { 

       $sql .= " name LIKE '%$each%' "; 
      } 
     } 

      $sql .= ") UNION ALL "; 

      $sql .= " (SELECT name AS type FROM person WHERE "; 
     foreach($search_explode as $each){ 
      $x++; 
      if($x == 1){ 
       $sql .= " name LIKE '%$each%'";}       
      else { 

       $sql .= " name LIKE '%$each%' "; 
      } 
     } 

      $sql .= ") UNION ALL "; 

      $sql .= "(SELECT name AS type FROM event WHERE "; 
     foreach($search_explode as $each){ 
      $x++; 
      if($x == 1){ 
       $sql .= " name LIKE '%$each%'";}       
      else { 

       $sql .= " name LIKE '%$each%' "; 
      } 
     } 

     $sql .= ") "; 

     $q = $this->db->query($sql); 
     return $q = $q->num_rows() == 0 ? FALSE : $q->result(); 
    } 

的功能正在工作。我不知道的是如何知道哪些數據來自哪個表格,然後在頁面上顯示結果?

回答

1

也許,向每個SELECT的結果添加一個字段。

function search_keyword(){ 
     $keyword = trim($_POST['keyword']); 
     $search_explode = explode(" ", $keyword); 
     $x = 0; 

     $sql = " (SELECT name AS type, \"table_global_info\" as mytable FROM global_info WHERE "; 
     foreach($search_explode as $each){ 
      $x++; 
      if($x == 1){ 
       $sql .= " name LIKE '%$each%'";}       
      else { 

       $sql .= " name LIKE '%$each%' "; 
      } 
     } 

      $sql .= ") UNION ALL "; 

      $sql .= " (SELECT name AS type, \"person\" as mytable FROM person WHERE "; 
     foreach($search_explode as $each){ 
      $x++; 
      if($x == 1){ 
       $sql .= " name LIKE '%$each%'";}       
      else { 

       $sql .= " name LIKE '%$each%' "; 
      } 
     } 

      $sql .= ") UNION ALL "; 

      $sql .= "(SELECT name AS type, \"event\" as mytable FROM event WHERE "; 
     foreach($search_explode as $each){ 
      $x++; 
      if($x == 1){ 
       $sql .= " name LIKE '%$each%'";}       
      else { 

       $sql .= " name LIKE '%$each%' "; 
      } 
     } 

     $sql .= ") "; 

     $q = $this->db->query($sql); 
     return $q = $q->num_rows() == 0 ? FALSE : $q->result(); 
    } 

問候!

+0

它正在工作。感謝您的幫助 :) – Sasha 2012-03-29 10:50:57

0

在SELECT語句中插入重新列標識表: SELECT名稱類型, 'tab_x' 作爲from_table FROM global_info WHERE .... SELECT名稱類型, 'tab_x1' 作爲from_table FROM global_info WHERE

當您使用返回的值時,請檢查「from_table」字段以查看原始表格的結果來自