[英]Using pseudonym in WHERE clause in MYSQL query
Please don't bite me for this, but I'm new to mysql and I have some problem with using pseudonym in WHERE clause. 请不要为此而咬我,但是我是mysql的新手,在WHERE子句中使用笔名存在一些问题。 I thought that it is possible to use pseudonym for aggregate function, defined in the select statement.
我认为可以将笔名用于select语句中定义的聚合函数。 Here is my query
这是我的查询
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
But, I catch an error "Unknown column total in WHERE clause". 但是,我遇到了一个错误“ WHERE子句中的未知列总数”。 Could anyone tell me if it is right to do query like this?
有人可以告诉我是否可以执行这样的查询吗?
You can not use alias in the where clause. 您不能在where子句中使用别名。 You need to use that in
having
您需要使用
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
Instead of WHERE total >=2 you can use HAVING (total >= 2 ) 您可以使用HAVING(总计> = 2)来代替WHERE total> = 2。
HAVING: 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 );
Yo can not use an column alias in where clause. 您不能在where子句中使用列别名。 you have to use the expression
COUNT(e.id)
in where clasue or you can use the alias in a having clause: 您必须在
COUNT(e.id)
使用表达式COUNT(e.id)
,也可以在hading子句中使用别名:
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
or 要么
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.