将查询限制为查询的5个最低值,为变量的5个最低值

时间:2011-12-16 23:53:55

标签: php mysql

我想将下面的查询限制为5个结果。但不只是任何5个结果。 points的5个最低值。我怎么能这样做?

$side = "SELECT title, points, submissionid
             FROM submission 
            WHERE points >= '$sidepoints' 
         ORDER BY points DESC"; 

编辑:我希望按points降序排列结果。

4 个答案:

答案 0 :(得分:5)

在MySQL中:

$side = "SELECT title, points, submissionid
         FROM submission 
         WHERE points >= '$sidepoints' 
         ORDER BY points ASC
         LIMIT 5";

修改

您可以将以上查询与以下PHP代码一起使用,或使用其他SQL查询。

PHP反向结果(未经测试)

$q = mysql_query($side);
$results = array();
while($r = mysql_fetch_assoc($q))
{
    $results[] = $r;
}
$results = array_reverse($results);
foreach($results as $result)
{
    echo $result['points']; // etc
}

或SQL方式(未经测试 - 从this post找到)

SELECT title, points, submissionid 
FROM (
    SELECT title, points, submissionid
         FROM submission 
         WHERE points >= '$sidepoints' 
         ORDER BY points ASC
         LIMIT 5
) AS t1 ORDER BY points DESC

答案 1 :(得分:2)

尝试使用其他查询(子查询)

来订购查询结果
SELECT * FROM (
  SELECT title, points, submissionid
  FROM submission 
  WHERE points >= '$sidepoints' 
  ORDER BY points ASC
  LIMIT 5
) t ORDER BY t.points DESC

答案 2 :(得分:1)

如果您使用MYSQL,请使用LIMIT

$side = "SELECT title, points, submissionid
         FROM submission 
         WHERE points >= '$sidepoints' 
         ORDER BY points DESC
         LIMIT 5"; 

ansi sql使用TOP。这适用于sql server

 $side = "SELECT TOP 5 title, points, submissionid
             FROM submission 
             WHERE points >= '$sidepoints' 
             ORDER BY points DESC"; 

答案 3 :(得分:1)

SELECT ... ORDER BY points ASC LIMIT 5?