$query = "SELECT COUNT(id) FROM complaint WHERE ID_complntCategory = ?";
$complntCategory = $database->prepare($query);
try {
$complntCategory->execute(array());
$complntCategory->setFetchMode(PDO::FETCH_ASSOC);
foreach ($complntCategory as $key) {
$totaalM = $key['1'];
$totaalV = $key['2'];
$totaalG = $key['3'];
}
}
catch(PDOException $e) {
echo "Error";
}
上面你看到了我的PHP代码,这就是我想要做的:
我试图从表格中获取行数'投诉'分为3个不同的变量(totaalM,totaalV和totaalG)。 totaalM变量应包含行数' WHERE ID_complntCategory = 1'。
对于其他变量,' ID_complntCategory'应该是2和3 (' ID_complntCategory'是1,2或3)
应该有一种方法,我不必写3个查询,对吗?
我明显地接近这个错误的方式,我不确定如何解决这个问题...
答案 0 :(得分:1)
您要做的是将pivot
行称为列,但MySQL没有像其他RDBMS那样拥有数据透视表操作符,但您可以在一个查询中使用这样的case表达式:
SELECT
SUM(CASE WHEN ID_complntCategory = 1 THEN 1 ELSE 0 END) AS totaalM,
SUM(CASE WHEN ID_complntCategory = 2 THEN 1 ELSE 0 END) AS totaalV,
SUM(CASE WHEN ID_complntCategory = 3 THEN 1 ELSE 0 END) AS totaalG,
COUNT(Id) AS Total
FROM complaint;
或者你可以这样缩短:
SELECT
SUM(ID_complntCategory = 1) AS totaalM,
SUM(ID_complntCategory = 2) AS totaalV,
SUM(ID_complntCategory = 3) AS totaalG,
COUNT(Id) AS Total
FROM complaint;
这会给你这样的东西:
| totaalM | totaalV | totaalG | Total |
|---------|---------|---------|-------|
| 2 | 3 | 1 | 7 |
答案 1 :(得分:0)
在这里你需要一些魔法,包括特殊的SQL和PDO功能。
首先,您需要一个SQL查询,它在一个查询中为您提供所需的结果。为此,您需要GROUP BY运算符:
!Join [ ",", [ !Ref ListParam, !Ref StringParam ]]
它将为您提供按ID_complntCategory分割的计数。
接下来,您可以使用PDO的一个宏伟功能PDO::FETCH_KEY_PAIR获取模式,它将为您提供一个数组,其中键为类别ID且值为计数
A client error (ValidationError) occurred when calling the
ValidateTemplate operation: Template error: every Fn::Join object
requires two parameters, (1) a string delimiter and (2) a list of
strings to be joined or a function that returns a list of strings
(such as Fn::GetAZs) to be joined.
请注意,您永远不应仅仅为了说“错误”而捕获PDO错误。让PHP error reporting代替。