我的sql查询存在一些问题,这个问题过去常常会得到一个结合了所有城镇的玩家的流行音乐总数但由于某种原因它会给出错误的总流行音乐 我也被告知使用绑定参数,但我不确定它们是什么以及如何使用它们。任何帮助都会非常感谢你。
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$latitude = -838;
$longitude = -493;
$con = mysqli_connect('localhost','User','Password','Database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"Database");
$sql="SELECT towns.location_x, towns.location_y, players.*,
town_deltas.*, town_deltas.town_id,
sum( town_deltas.population ) as total_population
FROM `town_deltas`
LEFT JOIN players ON town_deltas.owner_id = players.player_id
LEFT JOIN towns ON town_deltas.town_id = towns.town_id
WHERE town_deltas.owner_id = '".$q."'
GROUP BY owner_id, data_timestamp
ORDER BY `town_deltas`.`town_id` ASC,
`town_deltas`.`data_timestamp` ASC";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>data_timestamp</th>
<th>name</th>
<td>population</td>
<td>location_x</td>
<td>location_y</td>
<td>distance</td>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['data_timestamp'] . "</td>";
echo "<td>" . $row['Player_name'] . "</td>";
echo "<td>" . $row['total_population'] . "</td>";
echo "<td>" . $row['location_x'] . "</td>";
echo "<td>" . $row['location_y'] . "</td>";
echo "<td>" . $row['distance'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
破了总弹出页面
data_timestamp name population
2016-09-25 00:03:29 Kodabear 50315100
应该显示什么
data_timestamp name population
2016-09-25 00:03:29 Kodabear 335,434
玩家表
player_id race_id alliance_id alliance_role_id Player_name
237186 1 78 381 Kodabear
town_deltas表
5198444 2016-09-21 00:03:47 282609 237186 01 Smokey The Bear 29634 0 0
5198445 2016-09-21 00:03:47 289820 237186 02 Littlebears 28557 0 0
5198446 2016-09-21 00:03:47 292694 237186 03 Panda-bear 28068 0 0
5198447 2016-09-21 00:03:47 296040 237186 04 Humphrey 29420 1 1
5198448 2016-09-21 00:03:47 296593 237186 05 Winnie-the-Pooh 29527 0 0
5198449 2016-09-21 00:03:47 296914 237186 06 Shayna The Bear 29287 0 0
5198450 2016-09-21 00:03:47 301887 237186 07 Basil the Bear 27684 0 0
5198451 2016-09-21 00:03:47 316315 237186 08 Gummybear 27546 0 0
5198452 2016-09-21 00:03:47 350576 237186 09 Paddington 28919 0 0
5198453 2016-09-21 00:03:47 365385 237186 10 Walkingbear 26369 0 0
5198454 2016-09-21 00:03:47 377604 237186 11 Panserbjørne 25636 0 0
5198455 2016-09-21 00:03:47 404089 237186 12 YogiBear 19672 0 0
5198456 2016-09-21 00:03:47 405583 237186 13 Baloo 3938 0 0
答案 0 :(得分:2)
城镇人口将一再重复。你不想要sum()
。只需采用max()
:
SELECT towns.location_x, towns.location_y, players.*,
town_deltas.*, town_deltas.town_id,
max( town_deltas.population ) as total_population
您的查询还有很多其他问题 - 尤其是SELECT
中未正确汇总的列。但是,这可能会解决您的直接问题。