我有一个查询,它在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";