我正在尝试从数据库中获取最后修改的行,现在我就这样了:
我的表:
My table:
id fort_id Last modified
------------------------------
1 1 today
2 1 yesterday
3 2 today
4 2 yesterday
5 2 day be4 yesterday
6 3 today
------------------------------
我想得到这样的信息:
id fort_id Last modified
------------------------------
1 1 today
3 2 today
6 3 today
------------------------------
现在这就是我的代码:
$sql = "SELECT f.id, f.lat, f.lon, f.name, f.url, s.fort_id, s.team, s.last_modified, s.slots_available
FROM forts AS f
LEFT JOIN fort_sightings AS s ON f.id=s.fort_id
ORDER BY s.last_modified DESC";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$sql_defender = "SELECT pokemon_id, owner_name, cp
FROM gym_defenders
WHERE fort_id = " . $row['id'] . "
ORDER BY cp DESC";
$result_defender = $mysqli->query($sql_defender);
$encode_defender = [];
while($defender = $result_defender->fetch_assoc()) {
$encode_defender[] = array("mon_cp" => $defender['cp'],
"mon_owner" => $defender['owner_name'],
"mon_id" => $defender['pokemon_id']);
}
$url = preg_replace("/^http:/i", "https:", $row['url']);
if($row['team'] == 1){ $team = "mystic";}
if($row['team'] == 2){ $team = "valor";}
if($row['team'] == 3){ $team = "instinct";}
$encode[] = array("id" => $row['id'],
"name" => $row['name'],
"image" => $url,
"team" => $team,
"modified" => $row['last_modified'],
"spots" => $row['slots_available'],
"lat" => $row['lat'],
"lng" => $row['lon'],
"defenders" => $encode_defender);
}
echo json_encode($encode, JSON_NUMERIC_CHECK);
这段代码应该像每次使用最新的last_modified一样挑选1 fort_id。
答案 0 :(得分:1)
您需要使用GROUP BY即
$sql = "SELECT f.id, s.fort_id, s.last_modified
FROM forts AS f LEFT JOIN fort_sightings AS s ON f.id=s.fort_id
GROUP BY s.fort_id
ORDER BY s.last_modified DESC";
$result = $mysqli->query($sql);