繁体   English   中英

查询在 MySQL 工作台中有效,但在 PHP 中无效

[英]Query works in MySQL Workbench but not in PHP

我有一个查询在 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 工作台中的结果:

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

结果在 PHP 网页中:

Computer Laptop, 1, 156.00000, , , , ,

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

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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM