php UPDATE和SELECT在同一个查询中

时间:2015-04-06 17:08:04

标签: php mysql database

我正在尝试在php中进行双重查询,并且由于某种原因无法正常工作。

Basicall我想在我的表中更新一行,其中id为MAX,fb_id等于fbId参数。

这是我的代码:

  public function updatePages($fbId, $nr_page = NULL) {
        $db = Database::getInstance();
        $query = "UPDATE visits SET pages =".$nr_page." WHERE id = (SELECT maxvalue FROM (SELECT MAX(id) AS maxvalue FROM visits WHERE fb_id =".$fbId."))";
        if($db->query($query))
            return true;
        return false;
    }

3 个答案:

答案 0 :(得分:0)

您可以尝试这种方式SELECT最大ID并分配给id WHERE子句

$query = "UPDATE visits SET pages =".$nr_page." WHERE id = (SELECT MAX(id) AS maxvalue FROM visits WHERE fb_id =".$fbId." LIMIT 1)";

答案 1 :(得分:0)

你需要两个级别吗?试试这个:

$query = "UPDATE visits SET pages =".$nr_page." WHERE id = (SELECT id FROM visits WHERE fb_id =".$fbId." ORDER BY id DESC LIMIT 1)";

答案 2 :(得分:0)

我最终成功了,这是解决方案:

  $query = "UPDATE visits SET pages =".$nr_page." WHERE fb_id =".$fbId." ORDER BY id DESC LIMIT 1";