gpt4 book ai didi

php - 我如何在一个 MySQL Select 查询中执行此操作,我想丢失 foreach 循环和第二个 select 查询?

转载 作者:行者123 更新时间:2023-11-29 00:08:24 26 4
gpt4 key购买 nike

<分区>

下面的代码给出了我想要的结果,但它涉及 2 个数据库查询。我宁愿用一个数据库查询来更有效地完成它。有没有一种方法可以构造 SELECT 语句,以便通过一个数据库查询为我提供下面所需的结果?

数据库表:费率

费率结构:id, seasonID, propID, rate

try {

$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");

$sql = "SELECT DISTINCT(seasonID), season.seasonDesc FROM `rates`
INNER JOIN season
ON rates.seasonID = season.id
WHERE propID = :propID";

$sqlprep = $conn->prepare($sql);

$ar_val = array(':propID'=>$propID);

if($sqlprep->execute($ar_val)) {
while($row = $sqlprep->fetch(PDO::FETCH_OBJ)){

$seasonID[$row->seasonDesc] = $row->seasonID;
//print_r($seasonID);

}

}
} catch(PDOException $e) {
echo $e->getMessage();
}

foreach($seasonID AS $key => $value){
echo "<b>".$key."</b>";
echo "<ul>";


try {

$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->exec("SET CHARACTER SET utf8");

$sql = "SELECT * FROM `rates`
WHERE seasonID = :seasonID
AND propID = 1
ORDER BY AccomType,rateType";

$sqlprep = $conn->prepare($sql);

$ar_val = array(':seasonID'=>$value);

if($sqlprep->execute($ar_val)) {
while($row = $sqlprep->fetch(PDO::FETCH_OBJ)){

echo "<li>".$row->accomType."<br>";
echo " ".$row->rateType." - ";
echo " R".number_format($row->rate,'2','.',' ')." ".$row->rateUnit."</li>";


}
}

}
catch(PDOException $e) {
echo $e->getMessage();
}
echo "</ul>";
}

没有 foreach 循环,我得到以下结果:

    Season 1 Property 1 rate: 1
Season 1 Property 2: rate 1
Season 1 Property 3: rate 1
Season 2 Property 1 rate: 1
Season 2 Property 2: rate 1
Season 2 Property 3: rate 1
Season 3 Property 1 rate: 1
Season 3 Property 2: rate 1
Season 3 Property 3: rate 1

期望的结果(foreach 循环给我这个结果):

Season 1
Property 1 rate: 1
Property 2: rate 1
Property 3: rate 1

Season 2
Property 1 rate: 1
Property 2: rate 1
Property 3: rate 1

Season 3
Property 1 rate: 1
Property 2: rate 1
Property 3: rate 1

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