选择最后5条记录并在PDO中按升序排序

时间:2015-06-30 08:59:26

标签: php mysql pdo

我想在表格中选择最后5条记录并按升序排序。首先,我想说我已经知道在stackoverflow上提供的这个问题的解决方案(如Select last 20 order by ascending - PHP/MySQL)。我遇到的问题是让它们在PDO中工作。这是我的代码:

$pdo = new PDO('mysql:host=localhost;dbname=somedb;port=3306', 'someuser', 'somepassword');
$stmval = $pdo -> prepare("SELECT * FROM (SELECT ID, col1, col2, col3 FROM table1 WHERE `col4` = 1 ORDER BY col3 DESC LIMIT 5) tmp ORDER BY col3 ASC" );
$stmval -> execute();
while($somesome = $stmval -> fetch())
{
echo $somesome ['col1'].",".$somesome ['col2'].",".$somesome ['col3'];
}

基本上它可以工作,直到我在prepare()中添加额外的SELECT * FROM(SELECT [...]) 如何选择表格中的最后5个元素并使用PDO对它们进行升序排序?

让我说我有阵列: 1,2,3,4,5,6,7,8,9,10 我选择mysql最后3个元素所以我需要使用DESC排序。我有: 1,10,9,8 现在我接受它并使其上升,所以最终的结果是我想要的: 8,9,10 问题是每当我尝试修改我的代码的第二行时:

stmval = $pdo -> prepare("SELECT [...] ORDER BY col3 DESC" );

stmval = $pdo -> prepare("SELECT * FROM (SELECT [...] ORDER BY col3 DESC) ORDER  BY col3 ASC" );

它不会因某种原因而工作。

2 个答案:

答案 0 :(得分:1)

我无法复制你的发现。

在MySQL中:

SELECT * 
  FROM 
     ( SELECT ID
            , col1
            , col2
            , col3 
         FROM table1 
        WHERE `col4` = 1 
        ORDER 
           BY col3 DESC LIMIT 5
     ) tmp 
 ORDER  
    BY col3 ASC;
+----+------+------+------+
| ID | col1 | col2 | col3 |
+----+------+------+------+
|  9 |   27 |   13 |   81 |
| 10 |   68 |   97 |   82 |
| 23 |   22 |   71 |   88 |
|  6 |   35 |   81 |   99 |
| 16 |   77 |   46 |  100 |
+----+------+------+------+

在PHP中:

27,13,81
68,97,82
22,71,88
35,81,99
77,46,100

答案 1 :(得分:0)

好吧,我已经设法解决了这个问题,我有点惭愧,我可能会错过它。

我的问题是,以下代码工作原因导致您不必将SELECT col3选择为ODRED BY:

$stmval = $pdo -> prepare("SELECT col1, col2 FROM table ORDER BY col3 DESC LIMIT 5");

以下情况中的Howether:

$stmval = $pdo -> prepare("SELECT * FROM (SELECT col1, col2 FROM table ORDER BY col3 DESC LIMIT 5) tmp ORDER BY col3 ASC);

你会得到错误,因为中间的SELECT不包括col3 最终正确的代码应该是:

$stmval = $pdo -> prepare("SELECT * FROM (SELECT col1, col2, col3 FROM table ORDER BY col3 DESC LIMIT 5) tmp ORDER BY col3 ASC);