我正在使用此PDO查询从MySQL调用数据。
$sql = "SELECT itemName FROM furniture WHERE itemID = :item";
在调用此特定itemName时,是否可以通过在同一查询中使用其itemID来获取下一个和上一个itemNames,而无需编写新查询来获取下一个和上一个itemNames?
e.g。 如果
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 Table
和Mahogani Black Chair
以及Thulang Relaxing Chair
答案 0 :(得分:2)
请使用此代码:
(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>";
}
?>
答案 1 :(得分:1)
$sql = "SELECT itemName FROM furniture WHERE itemID IN (:item-1, :item, :item+1) ORDER BY itemID";
为了迭代结果,您还可以使用PDO fetch() function来获取每一行。