如何在查询中包含变量的where子句中使用SQL UNION

时间:2017-03-06 13:05:58

标签: php mysql

我尝试使用UNION从两个表中检索数据但在我的情况下不起作用。 我正在尝试这个

    $folq = $db->query("select id as pid,folder,name as catname,name,thumb,pathc from hollywood where id = ".$parentid, database::GET_ROW) UNION ("select id as pid,folder,name as catname,name,thumb,pathc from bollywood where id = ".$parentid, database::GET_ROW);

但不适合我。请建议我如何实现。

4 个答案:

答案 0 :(得分:1)

您需要一个字符串查询(不是两个,在第二个查询中您不需要别名)

 $folq = $db->query("
  select 
      id as pid
      ,folder
      ,name as catname
      ,name
      ,thumb
      ,pathc 
  from hollywood 
  where id =  ".$parentid . 
  " UNION 
    select 
      id 
      ,folder
      ,name
      ,name
      ,thumb
      ,pathc 
  from bollywood 
  where id = ". $parentid

  , database::GET_ROW);

答案 1 :(得分:0)

我认为您的查询中存在语法错误,应该是这样的

 $folq = $db->query("select id as pid,folder,name as catname,name,thumb,pathc from hollywood where id = ".$parentid . " UNION select id as pid,folder,name as catname,name,thumb,pathc from bollywood where id = ".$parentid, database::GET_ROW);

答案 2 :(得分:0)

请使用此

        $folq = $this->db->query("
            select id as pid,folder,name as catname,name,thumb,pathc from hollywood where id = $parentid 
        UNION  
            select id as pid,folder,name as catname,name,thumb,pathc from bollywood where id = ".$parentid);

答案 3 :(得分:0)

这有效:)

         $folq = $db->query("
        select id as pid,folder,name as         catname,name,thumb,pathc from category where id         = $parentid 
           UNION  
            select id as pid,folder,name as         catname,name,thumb,pathc from punjabi where id         = ".$parentid, database::GET_ROW);