我要做的是计算公司拥有的在线游戏的土地总价值。每个城市的土地当前价值以acre_price的形式存储在city_list表中。公司拥有的英亩数量作为金额存储在company_land表中。因此,总价值将是acre_price * amount,并为公司拥有的每个城市进行此操作,然后将其全部添加。
acre_price无法存储在company_land表中的原因是因为它是一个不断变化的值 - 如果有足够的活动,它可以每隔几分钟更改一次,并且在两个不同的表中保持最新的土地价值做了很多工作。
这就是我想出来的,它已经成功了。它计算正确的值,但仅适用于公司拥有的1个城市(数据库中的最新条目)。我需要它来计算数据库中所有条目的值。我已经尝试在第二个查询中将fetch更改为fetchAll,但这破坏了代码并且只显示了白页。
有谁知道我需要做些什么来实现这个目标?
提前致谢:)
$sth = null; $count = 0; $data = array();
$sth = $dbh->prepare("SELECT * FROM company_land WHERE company_id = ?");
$company_land_query = $sth->execute(array($_GET['id']));
if($company_land_query){
while($row = $sth->fetch()){
$land_data = $row;
++$count;
}
if($count > 0){
$sth = null; $count = 0; $data = array();
$sth = $dbh->prepare("SELECT * FROM city_list WHERE city_id = ?");
$land_price_query = $sth->execute(array($land_data['city_id']));
while($row = $sth->fetch()){
$city_data = $row;
$land_value = $land_data['amount'] * $city_data['acre_price'];
}
}
}
答案 0 :(得分:1)
您可以使用单个SELECT
语句使用此类
SELECT SUM(l.amount * c.acre_price) total
FROM company_land l INNER JOIN
city_list c ON l.city_id = c.city_id
未经测试,因为尚未提供表格和样本数据的DDL。
答案 1 :(得分:0)
你过早关闭第一个while循环,它应该包含第二个循环,因为所有第一个循环正在计算从第一个查询返回的行数,并且只返回该查询的最后一行($ land_data在没有被使用的情况下被多次覆盖。
代码应该更好地工作,注意我已经移动了一些代码并删除了几行不需要的代码:
/*
* Prepare both queries here, moved the city_list query out from the loops, no
* need to prepare it multiple times.
*/
$sthLand = $dbh->prepare("SELECT * FROM company_land WHERE company_id = ?");
$sthCity = $dbh->prepare("SELECT * FROM city_list WHERE city_id = ?");
$land_value = 0;
if ($sthLand->execute(array($_GET['id']))) {
while($land_data = $sthLand->fetch()) {
if ($sthCity->execute(array($land_data['city_id']))) {
while($city_data = $sthCity->fetch()) {
$land_value += $land_data['amount'] * $city_data['acre_price'];
}
}
}
}
$ land_value包含公司拥有的土地总价值。