MySQL:如何将结果限制为最后5行

时间:2013-10-23 16:30:36

标签: php mysql

这显示最近10个新结果,一切正常

$query = "SELECT s.name AS song,
                 SUM(v.hit_shit) AS hit,
                 COUNT(v.hit_shit) - SUM(v.hit_shit) AS shit,
                 MAX(date_voted) AS last_vote
            FROM songs AS s
           INNER JOIN votes AS v ON v.song_id = s.id
           WHERE v.date_voted >= CURDATE()
           GROUP BY s.id
           ORDER BY last_vote DESC
           LIMIT 10";
$song = mysql_query($query);

但这显示全部,但我只需要5 :(

$query = "SELECT s.name AS song,
                 SUM(v.hit_shit) AS hit,
                 COUNT(v.hit_shit) - SUM(v.hit_shit) AS shit
            FROM songs AS s
           INNER JOIN votes AS v ON v.song_id = s.id
           WHERE v.date_voted >= CURDATE()
             AND v.date_voted < CURDATE() + INTERVAL 1 DAY
           GROUP BY s.id
           ORDER BY hit DESC, shit ASC, song ASC";
$song = mysql_query($query);

P.S。抱歉4我的坏人

2 个答案:

答案 0 :(得分:1)

在查询结尾添加限制5。

$query = "SELECT s.name AS song,
                 SUM(v.hit_shit) AS hit,
                 COUNT(v.hit_shit) - SUM(v.hit_shit) AS shit,
                 MAX(date_voted) AS last_vote
            FROM songs AS s
           INNER JOIN votes AS v ON v.song_id = s.id
           WHERE v.date_voted >= CURDATE()
           GROUP BY s.id
           ORDER BY last_vote DESC
           LIMIT 5";

$song = mysql_query($query);

答案 1 :(得分:0)

您应该在查询结尾添加参数“LIMIT”。

$query = "SELECT s.name AS song,
                 SUM(v.hit_shit) AS hit,
                 COUNT(v.hit_shit) - SUM(v.hit_shit) AS shit
            FROM songs AS s
           INNER JOIN votes AS v ON v.song_id = s.id
           WHERE v.date_voted >= CURDATE()
             AND v.date_voted < CURDATE() + INTERVAL 1 DAY
           GROUP BY s.id
           ORDER BY hit DESC, shit ASC, song ASC
           LIMIT 5";

$song = mysql_query($query);

编辑:修改代码格式。