如何在MySQL中限制ID

如何在MySQL中限制ID

我正在尝试从数据库中获取最后修改的行,现在我是这样的:

我的桌子:

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每次都选择一个fort_id。

最佳答案

您需要使用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);

关于php - 如何在MySQL中限制ID?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46136247/

10-10 22:09