PHP& MySQL:如何组合UPDATE和SELECT(与min函数)查询

时间:2012-11-06 20:54:58

标签: php mysql

我正在尝试从MySQL表中选择值最小的行,并使用PHP更新该行的标志列。但这对我不起作用。如果我把它分成两个查询,它可以工作,但结合这两个查询不会去任何地方。我做错了什么?

这是有效的:

$flag = 1;
$query = "SELECT MIN(value) FROM ". $myTable;
$data = mysqli_query($dbh, $query);
$dataSet = mysqli_fetch_row($data);
$value = $dataSet[0];
$queryUpdate = "UPDATE ". $myTable . " SET flag='" . $flag . "' WHERE value='" . $value. "'";
$dataUpdate = mysqli_query($dbh, $queryUpdate);

以下是我的尝试但失败了:

//attempt #1
$flag = 1;
$query = "UPDATE ". $myTable . " SET flag='" . $flag . "' WHERE value=( SELECT MIN(value) FROM '". $myTable . "')";
$data = mysqli_query($dbh, $query);

// attempt #2
$flag = 1;
$query = "UPDATE ". $myTable . " SET flag='" . $flag . "' ORDER BY value ASC LIMIT 1";
$data = mysqli_query($dbh, $query);

// attempt #3
$flag = 1;
$query = "UPDATE ". $myTable . " T1 
INNER JOIN ( SELECT MIN(value) FROM ". $myTable . " ) T2
ON T1.id = T2.id
SET T1.flag=" . $flag;
$data = mysqli_query($dbh, $query);

mysqli_error()返回

  

警告:mysqli_error()只需要1个参数,给定[在$ data = mysqli_query($ dbh,$ query)行中。]

任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:2)

看起来你差不多第三个选择了。

试试这个:

$query = "UPDATE ".$myTable." 
INNER JOIN (select min(value) as value from ".$myTable.") mintable on ".$myTable.".value = mintable.value    
SET flag = ".$flag;