在mysql中,LIMIT子句與select語(yǔ)句一起使用,以限制結(jié)果集中的行數(shù)。LIMIT子句接受一個(gè)或兩個(gè)offset和count的參數(shù)。這兩個(gè)參數(shù)的值都可以是零或正整數(shù)。
offset:用于指定要返回的第一行的偏移量。
Count:用于指定要返回的最大行數(shù)。
Limit子句接受一個(gè)或兩個(gè)參數(shù),當(dāng)指定兩個(gè)參數(shù)時(shí),第一個(gè)參數(shù)是偏移量,第二個(gè)參數(shù)表示計(jì)數(shù),而當(dāng)只指定一個(gè)參數(shù)時(shí),它表示從結(jié)果集開(kāi)始返回的行數(shù)。
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
LIMIT語(yǔ)法:
SELECT?column1,?column2,?... FROM?table_name LIMIT?offset,?count;
如下表“Data”,其中包含三列“Firstname”、“Lastname”和“Age”。
要從“Data”表中檢索前三行,我們將使用以下查詢(xún):
SELECT?*?FROM?Data?LIMIT?3;
要從“Data”表中檢索第2-3行(包括),我們將使用以下查詢(xún):
SELECT?*?FROM?Data?LIMIT?1,?2;
下面是php mysql實(shí)現(xiàn)查詢(xún)的代碼示例:
示例1:Limit條件
<?php $link = mysqli_connect("localhost", "root", "", "Mydb"); if ($link == = false) { die("ERROR: Could not connect. ".mysqli_connect_error()); } $sql = "SELECT * FROM Data LIMIT 2"; if ($res = mysqli_query($link, $sql)) { if (mysqli_num_rows($res) >?0)?{? ????????echo?"
Firstname | Lastname | Age |
---|---|---|
“.$row[‘Firstname’].” | “.$row[‘Lastname’].” | “.$row[‘Age’].” |
“;? ????????mysqli_free_result($res);? ????}? ????else?{? ????????echo?“No?matching?records?are?found.”;? ????}? }? else?{? ????echo?“ERROR:?Could?not?able?to?execute?$sql.?“.mysqli_error($link);? }? ?? mysqli_close($link);
輸出:
注:“res”變量存儲(chǔ)函數(shù)mysql_query()返回的數(shù)據(jù)。
每次調(diào)用mysqli_fetch_array()時(shí),它都會(huì)從res()集中返回下一行。
while循環(huán)用于遍歷表“data”的所有行。
示例2:使用面向對(duì)象方法的Limit子句
<?php $mysqli = new mysqli("localhost", "root", "", "Mydb"); if ($mysqli == = false) { die("ERROR: Could not connect. ".$mysqli->connect_error);? }? ?? $sql?=?"SELECT?*?FROM?Data?LIMIT?2";? if?($res?=?$mysqli->query($sql))?{? ????if?($res->num_rows?>?0)?{? ????????echo?"
Firstname | Lastname | Age |
---|---|---|
“.$row[‘Firstname’].” | “.$row[‘Lastname’].” | “.$row[‘Age’].” |
“;? ????????$res->free();? ????}? ????else?{? ????????echo?“No?matching?records?are?found.”;? ????}? }? else?{? ????echo?“ERROR:?Could?not?able?to?execute?$sql.?“.$mysqli->error;? }? ?? $mysqli->close();
輸出:
示例3:使用pdo方法的Limit子句
<?php try { $pdo = new PDO("mysql:host=localhost;dbname=Mydb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE,?PDO::ERRMODE_EXCEPTION);? }? catch?(PDOException?$e)?{? ????die("ERROR:?Could?not?connect.?".$e->getMessage());? }? ?? try?{? ????$sql?=?"SELECT?*?FROM?Data?LIMIT?2";? ????$res?=?$pdo->query($sql);? ????if?($res->rowCount()?>?0)?{? ????????echo?"
Firstname | Lastname | Age |
---|---|---|
“.$row[‘Firstname’].” | “.$row[‘Lastname’].” | “.$row[‘Age’].” |
“;? ????????unset($res);? ????}? ????else?{? ????????echo?“No?matching?records?are?found.”;? ????}? }? catch?(PDOException?$e)?{? ????die(“ERROR:?Could?not?able?to?execute?$sql.?“.$e->getMessage());? }? ?? unset($pdo);
輸出:
相關(guān)推薦:《mysql教程》
本篇文章就是關(guān)于mysql中l(wèi)imit用法詳解,希望對(duì)需要的朋友有所幫助!