0

任何人都可以帮助我如何从多个 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); 
        ?>

我搜索谷歌发现解决方案是使用联合,但我不断收到错误“未定义索引 t”

4

3 回答 3

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']
于 2013-04-21T16:38:25.913 回答
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
于 2013-04-21T16:35:49.783 回答
0

在您的选择查询中没有看到名为“t”的字段?尝试var_dump() $rows,然后您可能会看到出了什么问题。

您正在做的是尝试选择表别名。您不能选择它们,只能选择字段。

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

于 2013-04-21T16:36:02.180 回答