您好我试图将这样的多个总和加起来:
$_.PSIsContainer
但 SELECT
`users`.*,
@attackPower := FLOOR(SUM(IF( `weapons`.`weaponeType` = 'atk',`weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `attackPower` ,
@defencePower := FLOOR(SUM(IF( `weapons`.`weaponeType` = 'def', `weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `defencePower`,
@spyPower := FLOOR(SUM(IF( `weapons`.`weaponeType` = 'spy', `weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `spyPower`,
@uniPower := FLOOR(SUM(IF( `weapons`.`weaponeType` = 'uni', `weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `uniPower`,
(@attackPower + @defencePower + @spyPower + @uniPower) as `power`
FROM `users`
LEFT JOIN `weapons_has_users` ON `users`.`userId` = `weapons_has_users`.`userId`
LEFT JOIN `weapons` ON `weapons`.`weaponId` = `weapons_has_users`.`weaponId`
返回NULL
我能做些什么来解决这个问题?
答案 0 :(得分:1)
MySQL文档专门警告不要在同一语句中分配和使用变量。
此外,如果要在查询中使用聚合函数(并且希望返回多行),则需要子查询。
因为您需要使用聚合,所以您也可以使用子查询:
select u.*,
(attackPower + defencePower + spyPower + uniPower) as `power`
from (SELECT `users`.*,
FLOOR(SUM(IF( `weapons`.`weaponeType` = 'atk',`weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `attackPower` ,
FLOOR(SUM(IF( `weapons`.`weaponeType` = 'def', `weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `defencePower`,
FLOOR(SUM(IF( `weapons`.`weaponeType` = 'spy', `weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `spyPower`,
FLOOR(SUM(IF( `weapons`.`weaponeType` = 'uni', `weapons`.`weaponPower` * `weapons_has_users`.`count` , 0 ) )) AS `uniPower`,
FROM `users` LEFT JOIN
`weapons_has_users`
ON `users`.`userId` = `weapons_has_users`.`userId` LEFT JOIN
`weapons`
ON `weapons`.`weaponId` = `weapons_has_users`.`weaponId`
GROUP BY users.id
) u;