我试图使用LIMIT和OFFSET从数据库检索记录,效果很好,但是当我在末尾添加ORDER BY id时,它将失败.
我的代码是这样的:(这个很好用)
$sql6 = "SELECT * FROM products WHERE cat = 'category' LIMIT 10 OFFSET 0";
$result6 = $conn->query($sql6);
if ($result6->num_rows > 0) {
while($row6 = $result6->fetch_assoc()) {
echo $row6["position"];
} } else{}
在添加ORDER之后,它不会显示任何记录:
$sql6 = "SELECT * FROM products WHERE cat = 'category' LIMIT 10 OFFSET 0 ORDER BY id DESC";
$result6 = $conn->query($sql6);
if ($result6->num_rows > 0) {
while($row6 = $result6->fetch_assoc()) {
echo $row6["position"];
} } else{}
任何帮助表示赞赏.
解决方法:
LIMIT必须在语句的末尾:
SELECT * FROM products WHERE cat = 'category' ORDER BY id DESC LIMIT 10 OFFSET 0
SELECT
[ALL | DISTINCT | DISTINCTROW ]
[HIGH_PRIORITY]
[STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
[SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr …]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], … [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], …]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE ‘file_name’
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE ‘file_name’
| INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
BTW:执行语句后检查错误