gpt4 book ai didi

php - 在同一查询中获取下一条和上一条记录

转载 作者:可可西里 更新时间:2023-11-01 06:33:44 28 4
gpt4 key购买 nike

我正在使用此 PDO 查询从 MySQL 调用数据。

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

在调用这个特定的 itemName 时,是否可以通过在同一个查询中使用其 itemID 来获取下一个和上一个 itemName,而不必编写新查询来获取下一个和上一个 itemName?

例如如果

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);

我正在寻找 Teak Round TableMahogani Black ChairThulang Relaxing Chair

最佳答案

请使用此代码:

(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)

例如代码:

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>";
}
?>

关于php - 在同一查询中获取下一条和上一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31065277/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com