Php 从具有3个唯一ID的表中获取值(冗余sql查询)

Php 从具有3个唯一ID的表中获取值(冗余sql查询),php,mysql,pdo,Php,Mysql,Pdo,上面是我的PHP代码,下面是我要做的: 我试图将“投诉”表中的行数转换为3个不同的变量totaalM、totaalV和totaalG。totaalM变量应包含“其中ID_complntCategory=1”的行数 对于其他变量,“ID_complntCategory”应为2和3 “ID_complntCategory”为1、2或3 应该有一种方法,我不必写3个查询,对吗 很明显,我的做法是错误的,我不确定该如何解决这个问题…您尝试的是将行透视到列,但MySQL没有像其他RDBMS那样的透视表运算

上面是我的PHP代码,下面是我要做的:

我试图将“投诉”表中的行数转换为3个不同的变量totaalM、totaalV和totaalG。totaalM变量应包含“其中ID_complntCategory=1”的行数

对于其他变量,“ID_complntCategory”应为2和3 “ID_complntCategory”为1、2或3

应该有一种方法,我不必写3个查询,对吗


很明显,我的做法是错误的,我不确定该如何解决这个问题…

您尝试的是将行透视到列,但MySQL没有像其他RDBMS那样的透视表运算符,但您可以在一个查询中使用这样的case表达式:

$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";
   }
或者您可以将其缩短,如下所示:

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;
这将为您提供如下信息:

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;

这里你需要一些魔法,包括特殊的SQL和PDO特性

首先,您需要一个SQL查询,它在一个查询中为您提供所需的结果。要获得该信息,您需要操作员分组:

| totaalM | totaalV | totaalG | Total |
|---------|---------|---------|-------|
|       2 |       3 |       1 |     7 |
它将为您提供按ID\u complnt分类的计数

接下来,您可以使用PDO的一个重要特性fetch mode,它将为您提供一个数组,其中键是category id,值是count

SELECT ID_complntCategory, count(*) FROM complaint GROUP BY ID_complntCategory

请注意,您永远不应该捕捉到PDO错误而只是说错误。让我们来做吧。

您可能还需要使用IN和GROUP BY。。。选择ID_complntCategory,COUNTid FROM complaint WHERE ID_complntCategory IN[list_of_ID's]GROUP BY ID_complntCategory