在PHP中结合第二个总数查询来进行条件循环

时间:2018-11-30 23:47:03

标签: php mysql mysqli

我有一个带有脚本的PHP页面,该脚本显示基于所选“年”的行。这是通过URL字符串中的$ _GET执行的,然后在我的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(现在<= {{1 }}值。

是否有一种方法可以在其中添加一个子查询,该子查询为我提供UNION查询的总​​计数作为一列,例如:

$_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 / else子句在PHP中进行条件格式设置。

1 个答案:

答案 0 :(得分:0)

虽然很难确定没有样本数据,但根据您的评论,我认为您可以通过在所有日期<= $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;