4

我试图在我的 sql 中使用相同的参数,但它只识别第一个。看我的代码:

$stmt = $dbh->prepare("SELECT
    (SELECT SUM(oq.value)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user AND o.type = 1 AND oq.status = 1
    ) AS total_incomes_open,

    (SELECT SUM(oq.value)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user AND o.type = 1 AND oq.status = 2
    ) AS total_incomes_wroteoff");

$stmt->bindParam(":user", $this->getId());
$stmt->execute();

那可能吗?

4

1 回答 1

5

不可能重用这样的参数。您必须制作独特的参数:

$stmt = $dbh->prepare("SELECT
    (SELECT SUM(oq.value)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user_a AND o.type = 1 AND oq.status = 1
    ) AS total_incomes_open,

    (SELECT COUNT(oq.id)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user_b AND o.type = 1 AND oq.status = 2
    ) AS total_incomes_wroteoff");

$stmt->bindParam(":user_a", $this->getId());
$stmt->bindParam(":user_b", $this->getId());
$stmt->execute();

手册

当您调用 PDOStatement::execute() 时,您必须为希望传递给语句的每个值包含一个唯一的参数标记。您不能在准备好的语句中两次使用同名的命名参数标记。您不能将多个值绑定到单个命名参数,例如 SQL 语句的 IN() 子句。

于 2012-11-27T14:14:56.853 回答