读书人

分析一条sql话语的意思-

发布时间: 2012-10-14 14:55:08 作者: rapoo

分析一条sql语句的意思----------------
是mysql的

demo 表name val两列 按name分组 取分组后每组的前两个值
下面的sql语句是正确的,我有试过,就是不懂它的意思
求解。。。。。。

SQL code
select a.* from demo a where 2 > ( select count(*) from demo where name = a.name and val > a.val ) 


这where 2>是啥意思,这条语句给分析下

[解决办法]
select a.*,(select count(*) from demo where name = a.name and val > a.val) as col3
from demo a
试试这个,实际上按组排序,取序号小于2的就是每组前两个。
[解决办法]
如果你这样看着不明白,那你看下面的
SQL code
--1select a.*,(select count(*) from demo where name = a.name and val > a.val )from demo a where 2 > ( select count(*) from demo where name = a.name and val > a.val ) --2select * from (select a.*,(select count(*) from demo where name = a.name and val > a.val ) as cnt) t where cnt >2
[解决办法]
就是说 a 表中的每一行 与 demo 表比较 :
name = a.name and val > a.val 这个是关联条件
这个
select count(*) from demo where name = a.name and val > a.val
在name相同的情况下,返回当整张表VAL比当前行VAL大的个数

读书人网 >SQL Server

热点推荐