在php中为条件循环合并第二个总计数查询

rqdpfwrv  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(329)

我有一个带有脚本的php页面,它根据所选的“年”显示行。这是由$\u get from url字符串执行的,然后在mysql查询中使用一个变量。 $jID = (int)$_GET['id']; ```
SELECT lh., c.country AS c, c.flag, MAX(countv) countv, MAX(counta) counta
FROM (
SELECT vg.vertrekluchthaven AS code, count(
) as countv, 0 as counta
FROM tbl_vluchtgegevens vg
WHERE year(vg.vertrekdatum2) = '$jID'
GROUP BY vg.vertrekluchthaven

UNION  

  SELECT vg.aankomstluchthaven AS code, 0 as countv, count(*) as counta
  FROM tbl_vluchtgegevens vg  
  WHERE year(vg.vertrekdatum2) = '$jID'
  GROUP BY vg.aankomstluchthaven

) vg

LEFT JOIN tbl_luchthaven lh
ON lh.luchthavenID = vg.code

LEFT JOIN tbl_countries c
ON lh.countryID = c.countryID

GROUP BY vg.code
ORDER BY lh.luchthavencode;
``` ?id=2018 可能产生

| Code | Name                       | # Arrival | # Depart |
| AMS  | Amsterdam                  | 3         | 2        |
| MSP  | Minneapolis                | 5         | 5        |
| TLL  | Tallinn                    | 1         | 1        |

我还想对所有行进行计数,然后在循环中使用粗体和红色(或其他格式)的条件,如果整个表的计数小于等于0,那么现在小于等于 $_GET 价值观。
有没有一种方法可以在其中添加一个子查询,将联合查询的总计数作为一列提供给我,例如:

| Code | Name                       | # Arrival | # Depart | # Total |
| AMS  | Amsterdam                  | 3         | 2        | 64      |
| MSP  | Minneapolis                | 5         | 5        | 122     |
| TLL  | Tallinn                    | 1         | 1        | 1       |

FROM (
          SELECT vg.vertrekluchthaven AS code, count(*) as countv, 0 as counta
          FROM tbl_vluchtgegevens vg
          WHERE year(vg.vertrekdatum2) <= '$jID'
          GROUP BY vg.vertrekluchthaven

        UNION  

          SELECT vg.aankomstluchthaven AS code, 0 as countv, count(*) as counta
          FROM tbl_vluchtgegevens vg  
          WHERE year(vg.vertrekdatum2) <= '$jID'
          GROUP BY vg.aankomstluchthaven
       ) vg

然后我就可以用 if ($row['totalcount'] >0) /php中用于条件格式的else子句。

23c0lvtd

23c0lvtd1#

虽然没有示例数据很难确定,但根据您的评论,我认为您可以通过在所有日期上运行子查询来实现所需的功能 <= $jID 然后使用条件聚合得到您感兴趣的特定年份的值:

SELECT lh.*, c.country AS c, c.flag, 
       SUM(CASE WHEN vg.year = '$jID' THEN countv END) AS countv, 
       SUM(CASE WHEN vg.year = '$jID' THEN counta END) AS counta,
       SUM(counta)+SUM(countv) AS total
FROM (
      SELECT vg.vertrekluchthaven AS code, year(vg.vertrekdatum2) AS year, count(*) as countv, 0 as counta
      FROM tbl_vluchtgegevens vg
      WHERE year(vg.vertrekdatum2) <= '$jID'
      GROUP BY code, year

    UNION  

      SELECT vg.aankomstluchthaven AS code, year(vg.vertrekdatum2) AS year, 0 as countv, count(*) as counta
      FROM tbl_vluchtgegevens vg  
      WHERE year(vg.vertrekdatum2) <= '$jID'
      GROUP BY code, year
   ) vg

LEFT JOIN tbl_luchthaven lh
ON  lh.luchthavenID = vg.code

LEFT JOIN tbl_countries c
ON lh.countryID = c.countryID 

GROUP BY vg.code
ORDER BY lh.luchthavencode;

相关问题