简体   繁体   English

如何从mysql查询max id?

[英]How to query the max id from mysql?

I have search some resources, but I still unable to make it. 我搜索了一些资源,但我还是无法做到。 I would like to retrieve the data from the max id. 我想从max id中检索数据。 I have some codes in .php to make query 我在.php中有一些代码来进行查询

<?php

$DB_HostName = "mysql8.000webhost.com";
$DB_Name = "";
$DB_User = "";
$DB_Pass = "";
$DB_Table = "";

$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error()); 
mysql_select_db($DB_Name,$con) or die(mysql_error()); 

$query = "SELECT MAX(id),recommendData,room,level  FROM $DB_Table";

$res = mysql_query($query,$con) or die(mysql_error());

mysql_close($con);

$rows = array();

while ($r = mysql_fetch_assoc($res))
{
    $row["maxid"] = array(
        "level" => $r["level"],
        "recommendData" => $r["recommendData"],
        "room" => $r["room"],
        "id" => $r["MAX(id)"]
    );
}

header('Content-type: application/json');

echo json_encode($row);
die;
?>

the result shows like this: 结果显示如下:

{"maxid":{"level":"2","recommendData":"8","room":"4F","id":"4"}}

the the id is right, but data of level, recommendData, room are from the first id. id是正确的,但是level,recommendationData,room的数据来自第一个id。 Do I make something wrong?? 我做错了什么?

You can try 你可以试试

$query = "SELECT id,recommendData,room,level  FROM $DB_Table ORDER BY id DESC LIMIT 1";

Because currently you are fetching the max id plus the other info 因为目前您正在获取最大ID加上其他信息

-- -

Please do not use mysql_* functions. 请不要使用mysql_ *函数。

Use MySQLi or PDO instead 请改用MySQLiPDO

You can read on why more here 你可以在这里阅读更多信息

The right way to do the query is: 执行查询的正确方法是:

SELECT id, recommendData, room, level
FROM $DB_Table
ORDER BY id desc
LIMIT 1;

That is, don't do an aggregation at all. 也就是说,根本不要进行聚合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM