在mySQL查询中使用MAX()会产生有问题的结果

时间:2014-03-24 01:11:01

标签: php mysql sql

我尝试进行多次查询,以便通过用户名查找数据库中的最新条目 这是我的代码:

<?php  
    require_once("../includes/db_connection.php");  

    $userID = $_POST["userID"];
    $returnString = array();

    // Query the max id value of a given key_id (find the most recent upload)
    $query = "SELECT MAX(id) FROM photos WHERE key_id = {$userID}";
    $result = mysqli_query($connection, $query);
    //additional while loop could go here

    //now get the url where from the max id value that we just queried
    $query = "SELECT url FROM photos WHERE id = {$urlID}";
    $result = mysqli_query($connection, $query);

    $returnString['url'] = $urlID;

    mysqli_free_result($result);        
    echo json_encode($returnString);


?>

我认为问题在于第一个查询。当我从中返回结果时,我得到:

{"maxID": "current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

当我创建一个while循环来捕获数组时(为什么我需要这样做是因为它只会返回1个值):

while($row = mysqli_fetch_assoc($result)) {$returnString[] = $row;} 

然后我得到了这个时髦的结果:

[{"MAX(id)":"30"}] 

30是正确的值,但后来我不知道如何在我的下一个mySQL查询中使用该结果。

** * ** * **** 更新 * ** * ** * ** * ** < EM> *

查询:

SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID});

从mySQL内部进行查询时效果很好,但是我的php脚本无法正常工作。它返回这个奇怪的字符串:

{"url":{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}} 

这是更新后的脚本:

require_once("../includes/db_connection.php");  

$userID = $_POST["userID"];
$returnString = array();

$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);

mysqli_free_result($result);    

$returnString['url'] = $result; 
echo json_encode($returnString);

3 个答案:

答案 0 :(得分:2)

除非我在模式中遗漏了代码和注释中不明显的内容,否则可以通过组合SQL命令来保存自己的往返。

$query = "SELECT id AS urlID, url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";

然后像往常一样与你的结果对话。

答案 1 :(得分:1)

更新回答:

$query = "SELECT url FROM photos WHERE id = (SELECT MAX(id) FROM photos WHERE key_id = {$userID})";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result):
$url = $row['url'];
echo json_encode($url);
mysqli_free_result($result);

答案 2 :(得分:1)

我认为真正的问题在于循环并使用数组来获得结果。

您应该更改为单个查询,如:

SELECT url, MAX(id) as id FROM photos WHERE key_id = {$userID}

MAX(id) as id将聚合列名称返回为id

如果您只想要一行,则无需使用while循环。只需将while更改为if即可测试是否返回任何行,并将值分配给单个变量:

$id = {$row['id']};
$url = {$row['url']};

“时髦”的结果是尝试打印不需要的数组并存储了列名和值。