sum()as x在mySQL的where语句中看不到x

时间:2017-02-09 05:17:11

标签: mysql inner-join

我有一个带有两个连接的mySQL语句:

SELECT a.userID,  sum(b.score) as totalScore, c.userName FROM b
  Inner Join a on b.noteID = a.noteID
  Inner Join user on c.userID =  a.userID
  Where totalScore != 0
  group by a.userID  order by totalScore desc

但是当我运行查询时,它无法破译我用as

标记的总和
LIMIT 0, 1000   Error Code: 1054. Unknown column 'totalScore' in 'where clause' 0.18

1 个答案:

答案 0 :(得分:3)

使用having子句

  select a.userID, c.userName, 
         sum(b.score) as totalScore
  FROM b
  Inner Join a on b.noteID = a.noteID
  Inner Join user on c.userID =  a.userID
  group by a.userID, c.userName 
  having totalScore != 0
  order by totalScore desc
  1. 您无法使用select子句
  2. where的别名
  3. totalScore是一个引用整个组而不只是单个记录的值,因此您必须将其放入having
  4. 您不应选择c.userName,因为它既未汇总,也未汇总在group by子句中。在strict模式下,MySQL抛出错误,其他数据库引擎将始终抛出错误