MySQl错误:#1140 - 如果没有GROUP BY子句,混合GROUP列(MIN(),MAX(),COUNT(),...)没有GROUP列是非法的

时间:2015-09-15 12:16:37

标签: php mysql

我有一个查询来计算选择总和和列值的表格中每列的总和。

    $query = "select sum(salleryallowance), 
sum(entertainmentexp),
sum(depreciation), 
sum(electricity), 
sum(securitygard),
sum(machinaryrepaire), 
sum(totalrepairing),
sum(othermaintanaice),
sum(postal_charge),
sum(officeexp), 
sum(stationary),
sum(rent_lease_thresher), 
sum(rent_tractor), 
sum(traivlingallowance),
sum(transportaion_cost), 
sum(bank_commition), 
sum(total_exp),
sum(interest_earned), 
bit_farm.name as fname, 
bit_regional.name as rname 
from bit_income_expenditure 
inner join bit_farm on bit_income_expenditure.farm_id = bit_farm.id 
inner join bit_regional on bit_income_expenditure.region_id = bit_regional.id
";
$fetch = mysql_query($query);

$row = mysql_fetch_array($fetch);

// and print my output

echo $row[0]; //and so on....

执行此代码时,会显示以下错误:

如果没有GROUP BY子句,混合GROUP列(MIN(),MAX(),COUNT(),...)没有GROUP列是非法的

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

您的select条款包括:

 bit_farm.name as fname, bit_regional.name as rname 

默认情况下,MySQL会接受此操作,但您的系统必须具有符合ANSI标准的默认设置。

这取决于你想要什么。如果您想为每个“farm”和“region”设置不同的值,请添加:

 group by bit_farm.name, bit_regional.name 

如果您想要总计,请从select

中删除这些列

答案 1 :(得分:0)

如果您使用sum(),avg(),count()等任何函数,那么默认情况下它将汇总/计算/平均所有数据但是如果您使用任何其他要根据的列进行分类你的总和/计数/平均然后你必须在where子句之后提到group by,所以你的查询应该是 -

select sum(salleryallowance), 
sum(entertainmentexp),
sum(depreciation), 
sum(electricity), 
sum(securitygard),
sum(machinaryrepaire), 
sum(totalrepairing),
sum(othermaintanaice),
sum(postal_charge),
sum(officeexp), 
sum(stationary),
sum(rent_lease_thresher), 
sum(rent_tractor), 
sum(traivlingallowance),
sum(transportaion_cost), 
sum(bank_commition), 
sum(total_exp),
sum(interest_earned), 
bit_farm.name as fname, 
bit_regional.name as rname 
from bit_income_expenditure 
inner join bit_farm on bit_income_expenditure.farm_id = bit_farm.id 
inner join bit_regional on bit_income_expenditure.region_id = bit_regional.id
group by bit_farm.name,bit_regional.name;