PHP / Sql - 尝试根据特定条件获取行的最大ID

时间:2014-04-10 11:23:49

标签: php mysql sql sql-server

我正试图从Sql表中获取具有特定条件的行的id号。

假设我有下一个标签 -

     id           sender           touser         message
    ----------------------------------------------------
    1            User1            User2           Hi
    2            User2            User1           Hello
    3            User3            User1           How r u
    4            User1            User3           r u there?
    5            User1            User2           Hey
    6            User2            User3           Hey

所以我想获得最大的id行号,其中User1作为发送者,User2作为to user。,意思是我想得到5号。

为了做到这一点,我使用了下一个PHP代码 -

$query = "SELECT sender, touser, max(id) as latest_id FROM messages WHERE sender = :sender, touser = :touser LIMIT 1 ";

$query_params = array(
    ':sender' => $_POST['sender'],
    ':touser' => $_POST['touser']
);

  try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    $response["success"] = 0;
    $response["message"] = "Database Error. Couldn't add post!";
    die(json_encode($response));
}

$row = $stmt->fetch();
$resultid = $row['id'];

$response["success"] = 1;
$response["message"] = $resultid;
echo json_encode($response);

问题是代码进入catch,我得到了 - Database Error。无法添加帖子! - 一直响应。

那我在这里做错了什么?

我猜我的SELECT语句导致问题。

任何想法如何才能得到我想要的结果?

感谢您提供任何帮助

3 个答案:

答案 0 :(得分:1)

WHERE sender = :sender, touser = :touser

应该是

WHERE sender = :sender AND touser = :touser

WHERE sender = :sender OR touser = :touser

AND - matching both 
OR - Matching just one of them

答案 1 :(得分:1)

试试这个:

SELECT sender, touser, max(id) as latest_id 
FROM messages 
WHERE sender = :sender AND touser = :touser 
GROUP BY sender,touser 
LIMIT 1 

答案 2 :(得分:1)

更改

$query = "SELECT sender, touser, max(id) as latest_id FROM messages WHERE sender = :sender, touser = :touser LIMIT 1 ";

$query = "SELECT sender, touser, max(id) as latest_id FROM messages WHERE sender = :sender AND touser = :touser LIMIT 1 ";