为什么不能在where子句中使用临时列?: n$ j; D h5 [/ K
例如,此查询: 8 [9 c5 ~* s4 j1 Y& o LSelect - V3 c1 T I/ S/ s1 b% \# h- k/ C
product_brand, : I( ~' u; l" o1 R. }) I) v# d (CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count * a1 n8 Q0 F/ W' Y+ CFROM ) b. o% R5 m9 L. L; { products 9 i, U. y' z" R5 R4 h& z" j+ D3 hWHERE ' x# b h: D* p8 a2 e+ |* k, N; D3 r
1 7 z3 S( }7 R N0 YGROUP BY ) S- B; j5 ?$ S v2 U7 ~1 v# B product_brand % f7 f7 `, V; g, N% a& p+ j+ a! M这将显示两列,一列称为product_brand,另一列称为brand_count。brand_count是即时创建的,始终为1或0,具体取决于是否有50个或该品牌的产品。, c# h( ~ n0 C& O" |
这一切对我来说都是有意义的,除了我不能仅brand_count = 1在以下查询中选择时:+ f5 R8 W7 }& m& y$ ?9 ~
Select ( E, T/ ^' H% `* a( J S2 L
product_brand, ) ]9 |$ s' ^% H% r" N3 Q+ @5 O ^
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count ! K m5 t' O* i1 Q TFROM . [. @) p7 b; q8 J* f& v! P
products 9 a5 P' o' h) r( q
WHERE d# {* z+ ^& L! q! |
brand_count = 1 ) A. |2 I# m% j) e, O& bGROUP BY 2 s: R. K7 [) t1 k3 ^
product_brand 1 K9 o5 e! [) c: l9 ^- ?7 Y! q0 `这给了我这个错误: : D# O% i! Y' K#1054 - Unknown column 'brand_count' in 'where clause'1 I+ f% S3 O; a' b* G d8 g
- @) S) Q% b; l+ S5 C. H解决方案:) t5 |. r, }% {& Y6 K: q* g
8 [5 }" t. m) y* ~; `- F
1 M1 {0 P% \3 b2 r) q" g. n
2 k% T. j/ L' y/ e5 D
使用HAVING来代替:$ E. |% C" d9 o% m& R. v
Select# ]& n" v% g- x8 p" k$ M
product_brand,+ y5 a5 E. Y3 Q! \6 _
(CASE WHEN COUNT(product_brand)>50 THEN 1 ELSE 0 END) AS brand_count* G8 T, g8 s( n; _+ ?9 N( K1 _
FROM products $ M, _' D. C9 q) W GROUP BY product_brand' E; G+ }( _7 Q) x: y
HAVING brand_count = 1/ x3 ]0 j( m+ \( ~7 b
WHERE被评估 前 的GROUP BY。HAVING被评估之后。