如何获取表格中的下一行?
`image_id` int(11) NOT NULL auto_increment
`image_title` varchar(255) NOT NULL
`image_text` mediumtext NOT NULL
`image_date` datetime NOT NULL
`image_filename` varchar(255) NOT NULL
如果当前图像为3,而下一个图像为7等,则无效:
$query = mysql_query("SELECT * FROM images WHERE image_id = ".intval($_GET['id']));
echo $_GET['id']+1;
我该怎么办?
感谢
答案 0 :(得分:11)
SELECT * FROM images WHERE image_id < 3 ORDER BY image_id DESC LIMIT 1 -- Previous
SELECT * FROM images WHERE image_id > 3 ORDER BY image_id LIMIT 1 -- Next
答案 1 :(得分:7)
如果您想圈出记录,可以使用:
-- previous or last, if there is no previous
SELECT *
FROM images
WHERE image_id < 12345 OR image_id = MAX(image_id)
ORDER BY image_id DESC
LIMIT 1
-- next or first, if there is no next
SELECT *
FROM images
WHERE image_id > 12345 OR image_id = MIN(image_id)
ORDER BY image_id ASC
LIMIT 1
与UNION相同,可能更有效率:
-- previous or last, if there is no previous
(SELECT * FROM images WHERE image_id < 12345 ORDER BY image_id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE image_id = (SELECT MAX(image_id) FROM images))
LIMIT 1
-- next or first, if there is no next
(SELECT * FROM images WHERE image_id > 12345 ORDER BY image_id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE image_id = (SELECT MIN(image_id) FROM images))
LIMIT 1
答案 2 :(得分:2)
你非常接近。试试这个:
$query = mysql_query("SELECT * FROM images
WHERE image_id > ".intval($_GET['id'])." ORDER BY image_id LIMIT 1");
<?php echo $_GET['id'] ?>
答案 3 :(得分:0)
为了热爱互联网,请不要自己构建SQL查询。使用PDO。