简体   繁体   English

获取同一查询中的下一个和上一个记录

[英]Get next and previous records within the same query

I'm having this PDO query to call data from a MySQL. 我正在使用此PDO查询从MySQL调用数据。

$sql = "SELECT itemName FROM furniture WHERE itemID = :item";

While calling for this particular itemName, is it possible to get the next and previous itemNames by using its itemID within this same query itself without having to write a new query to get the next and previous itemNames? 在调用此特定itemName时,是否可以通过在同一查询本身中使用其itemID来获取下一个和上一个itemName,而无需编写新查询来获取下一个和上一个itemName?

eg if 例如,如果

itemID   |   itemName
___________________________
553      |   Mahogani Black Chair
554      |   Teak Round Table
555      |   Thulang Relaxing Chair
556      |   Teak Relaxing Chair

$sql = "SELECT itemName FROM furniture WHERE itemID = :item";
$stmt = $connect->prepare($sql);
$stmt->execute(array(':item'=>"554"));
$rslt = $stmt->fetchAll(PDO::FETCH_ASSOC);

I'm looking away of getting Teak Round Table and Mahogani Black Chair and Thulang Relaxing Chair 我正在寻找Teak Round TableMahogani Black ChairThulang Relaxing Chair

Please use this code: 请使用以下代码:

(SELECT itemName FROM furniture WHERE itemID < 554 order by itemID desc limit 1) 
UNION
(SELECT itemName FROM furniture WHERE itemID >= 554 order by itemID asc limit 2)

For Example code : 例如代码:

MyTable:
================
id  Store_name
================
1   English
2   French
3   Tamil
4   Uk
5   US

<?php  
$con = mysqli_connect("localhost","root","ramki","ramki");
$sql = "(SELECT store_name FROM store WHERE id < 2 order by id desc limit 1) 
        UNION
        (SELECT store_name FROM store WHERE id >= 2 order by id asc limit 2)";
$query = mysqli_query($con,$sql);
while ($row = mysqli_fetch_assoc($query)) {
echo $row['store_name'];
echo "<br>";
}
?>
$sql = "SELECT itemName FROM furniture WHERE itemID IN (:item-1, :item, :item+1) ORDER BY itemID";

为了迭代结果,您还可以使用PDO fetch()函数来获取每一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM