开发者

Mysql Select Second Row

I have a mysql question.


I have a news section on my website, and I want to display the two latest items. If I do:

SELECT * FROM nieuws ORDER BY id DESC LIMIT 1

it selects the latest item, and now I want to select the second to last item.

Do you guys know how to do it?

/// EDIT

Now it doesn't work, here's my code: (I have connect included ;) )

            $select = mysql_query("SELECT * FROM nieuws ORDER BY id DESC LIMIT 1");
            while($row = mysql_fetch_assoc($select)) {
            $datum = $row['time'];
            $titel = $row['title'];
            $bericht = $row['message'];
            ?>
            <div class="entry">

                <span class="blue date"><?php echo "$datum"; ?></span>
                <h3><?php echo "$titel"; ?></h3>
                <p><开发者_高级运维?php echo "$bericht"; ?></p> <br />
            </div><!-- end of entry --> <?php } ?>
            <?php 
            $select2 = mysql_query("SELECT * FROM nieuws ORDER BY id DESC LIMI 1, 1");
            while($row2 = mysql_fetch_assoc($select2)) {
                $datum = $row2['time'];
                $titel = $row2['title'];
                $bericht = $row2['message'];
                ?>
            <div class="entry">
                <span class="green date"><?php echo "$datum"; ?> </span>
                <h3><?php echo "$titel"; ?></h3>
                <p><?php echo "$bericht"; ?></p>
            </div> <!-- end of entry --> <?php } ?>
        </div><!-- end of news --> 


SELECT * FROM nieuws ORDER BY id DESC LIMIT 2 - selects last 2 items

SELECT * FROM nieuws ORDER BY id DESC LIMIT 1, 1 - selects only second item


LIMIT can take two arguments:

SELECT ... LIMIT 1, 1


If you want to display the latest two items, then you can get both at the same time by limiting to 2 instead of 1. This means it's only one database hit to get the information you need.

SELECT * FROM nieuws
  ORDER BY id DESC
  LIMIT 2

Or if you only want the second row, you can give an offset to the LIMIT, to tell it which row to start from, (Although if you get the first row in one query, then get the second in another, you're doing two database hits to get the data you want, which can affect performance).

SELECT * FROM nieuws
  ORDER BY id DESC
  LIMIT 1, 1

You can find out more information on how to use the LIMIT clause in the MySQL documentation


SELECT * FROM table where id > (SELECT id FROM table order by id ASC limit 1,1) and id <= (select max(id) from table)


SELECT *
FROM promotion
WHERE id = 16037
ORDER BY RankID ASC LIMIT 1,1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜