gpt4 book ai didi

php - 如何在 mysql where 子句中使用 SUM?

转载 作者:行者123 更新时间:2023-11-29 05:27:22 24 4
gpt4 key购买 nike

我想根据查询中某列的总和获得结果。我有两个表:league_squads 和 league_experience。我想选择有经验的小队结果。

下面的查询获取阶梯上的所有小队,并根据他们的总经验按降序排列。我想对其进行修改,使其只获取实际有经验的小队。

$query_squads = "
SELECT
s.squad_id AS id, s.ladder_id, s.team_id AS team_id,
x.experience_id, x.squad_id, SUM(x.value) as total_exp
FROM league_squads AS s
LEFT JOIN league_experience AS x ON (s.squad_id = x.squad_id)
WHERE s.ladder_id = ".$ladder_id."
ORDER BY total_exp DESC
";

如果我使用下面的查询,我会收到一条错误消息,指出“total_exp”列不存在。

$query_squads = "
SELECT
s.squad_id AS id, s.ladder_id, s.team_id AS team_id,
x.experience_id, x.squad_id, SUM(x.value) as total_exp
FROM league_squads AS s
LEFT JOIN league_experience AS x ON (s.squad_id = x.squad_id)
WHERE s.ladder_id = ".$ladder_id."
AND total_exp > 0
ORDER BY total_exp DESC
";

这是我的表格:

CREATE TABLE IF NOT EXISTS `league_experience` (
`experience_id` int(15) NOT NULL,
`squad_id` int(15) NOT NULL,
`value` int(15) NOT NULL,
`date_earned` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`experience_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `league_squads`
--

CREATE TABLE IF NOT EXISTS `league_squads` (
`squad_id` int(15) NOT NULL AUTO_INCREMENT,
`team_id` int(15) NOT NULL,
`ladder_id` int(15) NOT NULL,
`date_joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`status` tinyint(1) NOT NULL,
`last_rank` tinyint(5) NOT NULL,
PRIMARY KEY (`squad_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

最佳答案

你必须这样查询

SELECT s.squad_id AS id, s.ladder_id, s.team_id AS team_id,
x.experience_id, x.squad_id, SUM(x.value) as total_exp
FROM league_squads AS s
LEFT JOIN league_experience AS x ON (s.squad_id = x.squad_id)
WHERE s.ladder_id = ".$ladder_id."
HAVING SUM(x.value) > 0
ORDER BY total_exp DESC

关于php - 如何在 mysql where 子句中使用 SUM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18585895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com