mysql union按表排列结果


mysqli union arrange results per talbe

我使用mysqli联合来搜索数据库,如下所示:

$search = security($_POST['search']);
$search_val = "%{$search}%";
$search_disp = '';
if($searchQ = $db->prepare(
    "(SELECT name AS `name1` FROM `table1` WHERE name LIKE ? LIMIT 8)
    UNION 
     (SELECT heading AS `name2` FROM `table2` WHERE heading LIKE ? LIMIT 8)
    ")){
        if($searchQ->bind_param("ss",$search_val,$search_val)){
            if($searchQ->execute()){
               $searchQ->store_result();
               if($searchQ->num_rows){
                  $searchQ->bind_result($search_result);
                  while($searchQ->fetch()){
                      $search_disp.='
                          <div>'.$search_result.'</div>
                      ';
                  } 
               }
            }
            else{echo '$db->error' exit();}
        }
        else{echo '$db->error' exit();}
    }
    else{echo '$db->error' exit();}
    echo $search_disp; exit();

我不知道如何实现是显示不同的结果取决于表它来自,因为我取两个结果作为相同的变量($search_result),例如:

if(result from table one){
    $search_disp.='
        <div class="talbe1">'.$search_result.'</div>
    ';
}
else if(result from table two){
    $search_disp.='
        <div class="talbe2">'.$search_result.'</div>
    ';
}
谁能帮我一下吗?

您可以添加额外的行tbl到结果集,然后使用它:

(SELECT 'table1' as tbl, name FROM `table1` WHERE name LIKE ? LIMIT 8)
UNION 
(SELECT 'table2' as tbl, heading AS name FROM `table2` WHERE heading LIKE ? LIMIT 8)