请不要咬我这个,但我是mysql的新手,我在WHERE子句中使用假名有些问题。我认为可以在select语句中定义的聚合函数使用假名。 这是我的查询
SELECT a.name, s.name, COUNT(e.id) as total FROM athletes a
INNER JOIN sports s on s.id = a.sport_id
INNER JOIN events e on s.id = e.sport_id
WHERE total >=2 GROUP BY a.name
但是,我收到错误“WHERE子句中的未知列总数”。 谁能告诉我这样做是否正确?
答案 0 :(得分:3)
您不能在where子句中使用别名。您需要在having
SELECT
a.name,
s.name,
COUNT(e.id) as total FROM athletes a
INNER JOIN sports s on s.id = a.sport_id
INNER JOIN events e on s.id = e.sport_id
GROUP BY a.name having total >=2
答案 1 :(得分:1)
而不是WHERE total> = 2你可以使用HAVING(总> = 2)
HAVING:
SELECT a.name, s.name, COUNT(e.id) as total
FROM athletes a
INNER JOIN sports s on s.id = a.sport_id
INNER JOIN events e on s.id = e.sport_id
GROUP BY a.name, s.name
HAVING (total >= 2 );
答案 2 :(得分:0)
Yo不能在where子句中使用列别名。你必须在where clasue中使用表达式COUNT(e.id)
,或者你可以在having子句中使用别名:
SELECT a.name, s.name, COUNT(e.id) as total FROM athletes a INNER JOIN sports s on s.id = a.sport_id INNER JOIN events e on s.id = e.sport_id WHERE COUNT(e.id)>=2 GROUP BY a.name
或
SELECT a.name, s.name, COUNT(e.id) as total FROM athletes a INNER JOIN sports s on s.id = a.sport_id INNER JOIN events e on s.id = e.sport_id having total>=2 GROUP BY a.name