【问题标题】:Query works in MySQL Workbench but not in PHP查询在 MySQL Workbench 中有效,但在 PHP 中无效
【发布时间】:2021-04-21 22:04:26
【问题描述】:

我有一个在 MySQL Workbench 中完美运行的查询,但在我的 PHP 网页中执行时将某些列返回为 NULL。

EverSQL 验证器 说存在语法错误,但没有指定它是什么,这没有帮助。谁能告诉我怎么了?

$query = "
SELECT CONCAT(ade.`type`, ' ', ade.subtype) AS `type`, 
COUNT(*) AS count, 
@total := SUM(ade.total_co2_kg) AS total, 
ROUND(SUM(ade.raw_materials) / @total * 100, 2) AS raw_materials, 
ROUND(SUM(ade.supplying) / @total * 100, 2) AS supplying, 
ROUND(SUM(ade.making) / @total * 100, 2) AS making, ROUND(SUM(ade.assembly) / @total * 100, 2) AS assembly, 
ROUND(SUM(ade.distribution) / @total * 100, 2) AS distribution
FROM glpi_plugin_gtm_computermodels_association AS ass_mod
JOIN glpi_plugin_gtm_ademe_co2_emissions_for_manufacture AS ade 
ON ass_mod.gtm_ademe_id = ade.id
GROUP BY ade.`type`, ade.subtype
ORDER BY total DESC";

$results = $DB->request($query);

foreach ($results as $result) {
    echo implode(', ', $result);
}

MySQL Workbench 中的结果:

'Computer Laptop', '1', '156.00000', '76.92', '1.21', '0.48', '1.22', '20.32'

PHP 网页中的结果:

Computer Laptop, 1, 156.00000, , , , ,

【问题讨论】:

  • 你不应该依赖于以后在同一个选择列表中能够使用@total
  • 我很困惑;你怎么知道一个子类型属于哪个类型?

标签: php mysql


【解决方案1】:

我找不到它在 PHP 中无法正常工作的原因,但我找到了一种解决方法,即不使用 SUM 运算符,然后将结果乘以计数...

【讨论】:

    【解决方案2】:

    MySQL 不保证SELECT 列表中的表达式将从左到右进行计算。所以你不能安全地使用在一个表达式中分配的变量在后面的表达式中。

    代替@total变量,每次都写出它的表达式。

    $query = "SELECT 
    CONCAT(ade.`type`, ' ', ade.subtype) AS `type`, 
    COUNT(*) AS count, 
    SUM(ade.total_co2_kg) AS total, 
    ROUND(SUM(ade.raw_materials) / SUM(ade.total_co2_kg) * 100, 2) AS raw_materials, 
    ROUND(SUM(ade.supplying) / SUM(ade.total_co2_kg) * 100, 2) AS supplying, 
    ROUND(SUM(ade.making) / SUM(ade.total_co2_kg) * 100, 2) AS making, ROUND(SUM(ade.assembly) / SUM(ade.total_co2_kg) * 100, 2) AS assembly, 
    ROUND(SUM(ade.distribution) / SUM(ade.total_co2_kg) * 100, 2) AS distribution
    FROM glpi_plugin_gtm_computermodels_association AS ass_mod
    JOIN glpi_plugin_gtm_ademe_co2_emissions_for_manufacture AS ade ON ass_mod.gtm_ademe_id = ade.id
    GROUP BY ade.`type`, ade.subtype
    ORDER BY total DESC";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      相关资源
      最近更新 更多