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

时间:2013-09-03 06:52:11

标签: php mysql sum where

我想根据查询中的列总和得到结果。我有两张桌子: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;

2 个答案:

答案 0 :(得分:2)

你必须像这样进行查询

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

答案 1 :(得分:1)

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 total_exp > 0
 ORDER BY total_exp DESC