1、select @cnt:=@cnt+1,tbl.* from tbl
返回的第一个列名为 @cnt:=@cnt+1
显然他不能作为列名出现在where子句中2、若写做 select @cnt:=@cnt+1 as cnt,tbl.* from tbl
但cnt同样不能出现在where子句中3、但是 select @cnt:=@cnt+1,tbl.* from tbl HAVING cnt=1
就可以了
返回的第一个列名为 @cnt:=@cnt+1
显然他不能作为列名出现在where子句中2、若写做 select @cnt:=@cnt+1 as cnt,tbl.* from tbl
但cnt同样不能出现在where子句中3、但是 select @cnt:=@cnt+1,tbl.* from tbl HAVING cnt=1
就可以了
select @cnt:=@cnt+1 as haha,tbl.*
from tbl HAVING haha=2mysql测试通过唠叨的第三点可能手误 select @cnt:=@cnt+1 as cnt,tbl.* from tbl HAVING cnt=1
SET @cnt =0;
select @cnt:=@cnt+1 as ttt,post.*
from post having ttt =1;
得出的结果是除了ttt=1的结果,很奇怪
而having ttt =2则没有结果环境是mysql5.0
SET @cnt =0;
select @cnt:=@cnt+1 as ttt,post.*
from post having ttt =1;
的结果是
ttt全部+1,郁闷
set @cnt=0
当执行where @cnt=1时,@cnt=0,所以不会有任何结果。@cnt=@cnt+1是有结果时才会执行的。
select @cnt:=@cnt+1 as ttt,post.*
from post having ttt =1having是在结果出来后再次执行sql的。
当ttt=1时,会再次执行@cnt:=@cnt+1,所以显示的ttt就=2了。不过数据其实还是第一条。
select @cnt:=@cnt+1 as haha,post.*
from post HAVING haha=2
mysql-5.0.13-rc-win32 在 phpMyAdmin 2.7.0-pl2 sql中可以正确执行
select @cnt:=@cnt+1 as ttt,post.*
from post having ttt =1having是在结果出来后再次执行sql的。
当ttt=1时,会再次执行@cnt:=@cnt+1,所以显示的ttt就=2了。不过数据其实还是第一条。那为什么出来的还是所有的数据,而不是第一条?
我的是mysql 4.0.20,由于其他应用项目的约束,只能用这个了“having是在结果出来后再次执行sql的”
这句话是错误的having 子句是在查询结果中过滤出符合条件的记录对于
SET @cnt =0;
select @cnt:=@cnt+1 as ttt,post.*
from post
having ttt =1;将先执行
select @cnt:=@cnt+1 as ttt,post.*
from post
得到
ttt ...
1 ...
2 ...
3 ...
然后在此结果中提取 ttt=1 的记录并返回
这句话是错误的在我们看来,你是错误的。因为在我们的版本用having后的确是再次执行了@cnt=:@cnt+1。
所以having的写法不建议使用。每一个版本都返回不同结果的语句敢用吗?
select @cnt:=@cnt+1,tbl.* from tbl where @cnt=1;
就的确不会有返回值,因为@cnt是在客户端才被加1的,而查询的时候,只有@cnt=0一条记录
我运行:
SELECT @cnt := @cnt +1, tbl. * FROM tbl WHERE @cnt =0;
的确只返回了一条。
而运行
SELECT @cnt := @cnt +1, tbl.* FROM tbl having @cnt =1;
是不会有返回值的,因为运行查询的时候@cnt还没有+1。
select @cnt:=@cnt+1 as haha,post.*
from post HAVING haha=2
mysql-5.0.13-rc-win32 在 phpMyAdmin 2.7.0-pl2 sql中可以正确执行-------------------------------------------------------------语法没问题,但不会有返回值,所以不能算是正确执行
----------------------
HAVING子句基本上是最后使用,只位于被发送给客户端的条目之前,
表达式发送到客户端后才进行计算
----------------------
这样看来having应该先执行,再计算表达式。不过这样好像不合理哦,而且结果也不是这样的。
在我的版本上表达式先计算了,然后having,表达式再次计算。4.0版的。