使用php union从多个表中选择数据

时间:2013-04-21 16:28:06

标签: php mysql

任何人都可以帮助我如何从多个MySQL表中进行选择,并使用php进行游戏限制15排序?

   <?php
   //$query = "SELECT id, gamename, gameplayed FROM action, adventure, augur, beauty, chess, joke, mmorpg, multiplayer, platform, puzzle, racing, shooting, sport, stratergy WHERE id = :id";
   $query = '
     SELECT id, gamename, gameplayed FROM((
     SELECT id, gamename, gameplayed 
     FROM action 
 ORDER BY gameplayed
 DESC LIMIT 15 
 ) UNION (
     SELECT id, gamename, gameplayed
     FROM adventure
     ORDER BY gameplayed
     DESC LIMIT 15
     ))as t ORDER BY gameplayed';

     $query_params = array(':id' => '1'); 
     //$query = "SELECT id, gamename FROM action, adventure, augur, beauty, chess, joke, mmorpg, multiplayer, platform, puzzle, racing, shooting, sport, stratergy ORDER BY gameplayed DESC LIMIT 15"; 
     try 
      { 
        // These two statements run the query against your database table. 
        $stmt = $db->prepare($query); 
        $stmt->execute($query_params); 
      } 
     catch(PDOException $ex) 
      { 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code.  
        die("Failed to run query: " . $ex->getMessage()); 
      } 

      $rows = $stmt->fetchAll(); 
        foreach($rows as $row):
        echo $rows['t'];
        endforeach;
        unset($row); 
        ?>

我搜索google发现解决方案是使用union,但我一直收到错误“undefine index t”

3 个答案:

答案 0 :(得分:0)

尝试将SQL查询更改为此

SELECT id, gamename, gameplayed 
FROM action 
LIMIT 15 
UNION
SELECT id, gamename, gameplayed
FROM adventure
ORDER BY gameplayed DESC 
LIMIT 15
ORDER BY gameplayed

答案 1 :(得分:0)

在您的选择查询中看不到名为“t”的字段?尝试var_dump() $rows,然后您可能会发现错误。

您正在尝试选择表别名。您无法选择它们,只能选择字段。

现在,您的结果应该按照$rows列中的顺序查看数组gameplayed的子数组的开头,例如第一个表的元素和第二个的混合子数。

答案 2 :(得分:0)

您是否尝试将UNION的所有结果选为别名't'?它不起作用,你必须逐个使用它们,即:

...UNION (
 SELECT t.id as 'tid', t.gamename as 'tgamename', t.gameplayed as 'tgameplayed'
 FROM adventure AS t
 ...


$row['tid']; $row['tgamename']; $row['tgameplayed']