如何在 where 子句中使用临时列
为什么不能在 where 子句中使用临时列?
例如,以下查询:
Select
product_brand,
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count
FROM
products
WHERE
1
GROUP BY
product_brand
这会显示两列,一列名为 product_brand
,一列名为 brand_count
。 brand_count
是动态创建的,并且始终为 1 或 0,具体取决于该品牌是否有 50 个或多个产品。
所有这些对我来说都是有意义的,除了我不能仅在 brand_count = 1
时进行选择,如下面的查询所示:
Select
product_brand,
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count
FROM
products
WHERE
brand_count = 1
GROUP BY
product_brand
这给了我这个错误:
#1054 - Unknown column 'brand_count' in 'where clause'
Why can't I use a temporary column in the where clause?
For example, this query:
Select
product_brand,
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count
FROM
products
WHERE
1
GROUP BY
product_brand
This brings up two columns, one called product_brand
and one called brand_count
. brand_count
is created on the fly and is always 1 or 0 depending on whether or not there are 50 or products with that brand.
All this makes sense to me, except that I can't select only if brand_count = 1
as in this query below:
Select
product_brand,
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count
FROM
products
WHERE
brand_count = 1
GROUP BY
product_brand
which gives me this error:
#1054 - Unknown column 'brand_count' in 'where clause'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
HAVING
代替:WHERE
在GROUP BY
之前评估。HAVING
之后进行评估。Use
HAVING
instead:WHERE
is evaluated before theGROUP BY
.HAVING
is evaluated after.因为在 SQL 中,首先“选择”列,然后“投影”列。
Because in SQL the columns are first "selected" and then "projected".
您必须使用完整子句,因此您需要:
这对于任何 SQL 语句中的任何计算字段都是相同的。
简单来说:
不会起作用,但是:
会起作用。 你的情况也是一样。
You have to use the full clause, so you will need:
This is the same for any calculated field in any SQL statement .
To simplify:
won't work, but:
will. It's the same in your case.
因为在完成处理之前它不知道该列是什么。
如果您想通过该名称访问该列,则必须使用子查询,否则您将必须在不使用您指定的名称的情况下限定该列,从而重复您的 case 语句。
Because it has no idea what that column is until after it's done the processing.
If you want to access the column by that name you would have to use a subquery, otherwise you are going to have to qualify the column without the name you gave it, repeating your case statement.
如果我正确地理解了您的意图,您可以重写此查询以读取:
这将为您提供所有具有
count > 的
并且还会告诉你product_brands
。 50每个的计数。
If I read your intent correctly, you can re-write this query to read:
This will give you all
product_brands
that have acount > 50
and will also show youthe count for each.