参数号无效,联合选择

时间:2013-11-18 23:52:24

标签: php mysql pdo

我真的无法在这里发现我的错误。

$query = <<<'BUM'
(
    SELECT ca.id, ca.name, ca.slug, ca.record_date, 2 AS complete, 0 AS numbers
    FROM  `cms_articles_article` ca
    WHERE record_date
    BETWEEN ':y_1 - :m_1 -01'
    AND ':y_2 - :m_2 -31'
    GROUP BY ca.id
    LIMIT 0, 3)
UNION ALL (
    SELECT ca.id, ca.name, ca.slug, ca.record_date, 1 AS complete, COUNT( ca.id ) AS numbers
    FROM  `cms_articles_article` ca
    WHERE YEAR( record_date ) = :y_3
    GROUP BY MONTH( record_date )
    )
UNION ALL (
    SELECT ca.id, ca.name, ca.slug, ca.record_date, 0 AS complete, COUNT( ca.id ) AS numbers
    FROM  `cms_articles_article` ca
    GROUP BY YEAR( record_date )
    )
ORDER BY 
complete ASC, 
record_date DESC
BUM;

$stmt = $db
->prepare($query)
;
$year = 2013;
$month = 12;
$stmt->execute(array(
    ':y_1' => $year, 
    ':y_2' => $year, 
    ':y_3' => $year, 
    ':m_1' => $month,
    ':m_2' => $month,
    ));

我考虑到了你无法重用命名参数的事实。如果从查询(和执行)中删除:y_3,它将正确运行。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

你不能在字符串中使用params。

':y_2 - :m_2 -31' - 只是一个字符串,0个参数

您的整个查询只有一个参数。

:y_2 - :m_2 -31 - 表达式,2个参数

答案 1 :(得分:0)

尝试在您的子查询上添加ALIAS,如:

UNION ALL (
 SELECT ca.id, ca.name, ca.slug, ca.record_date, 1 AS complete, COUNT( ca.id ) AS numbers
 FROM  `cms_articles_article` ca
 WHERE YEAR( record_date ) = :y_3
 GROUP BY MONTH( record_date )
) A
UNION ALL (
 SELECT ca.id, ca.name, ca.slug, ca.record_date, 0 AS complete, COUNT( ca.id ) AS numbers
 FROM  `cms_articles_article` ca
 GROUP BY YEAR( record_date )
) B