日期:2014-05-19  浏览次数:20485 次

sql 语句,看不明白。
表如下
id     name     content       sclass_name       ballot     monthStar
34     邓健     偶是第一       ECT212             10                 2007-5

我想得到每月份即(mothstar)中ballot值最大的人的姓名(name)

我看有人提供的答案是:
Select   *   from   表   as   t   where   not   exists(
    Select   *   from   表   where   monthStar=t.monthStar   and   ballot> t.ballot)

还有
select   *   from   T   as   tmp
where   not   exists(select   1   from   T   where   monthStar=tmp.monthStar   and   ballot> tmp.ballot)

这两句我看不明白什么意思。尤其是括号里面的,请哪位帮忙讲下。。。谢谢了。

------解决方案--------------------
用EXIST、IN效率比较低,用内连接高一些
SQL语句类似于自连接
如不存在monthStar=t.monthStar and ballot> t.ballot,则满足条件
------解决方案--------------------
看帮助
not exists的意思是不存在
------解决方案--------------------
Select * from 表1 as t where not exists(
Select * from 表1 where monthStar=t.monthStar and ballot> t.ballot)
简单这样里面吧,SELECT * FROM 表1 t WHERE条件是,
根据 monthStar=t.monthStar关联,拿ballot字段比较大小,从表1中找比t表(别名)更大的记录,要是没有找到就返回当前行。
不知道这样说楼主明白不明白,不明白可以找not exists相关帮助。


------解决方案--------------------
Select * from 表 as t where not exists(
Select * from 表 where monthStar=t.monthStar and ballot> t.ballot)

可以改成:

Select a.* from 表 as a,表 as b
where a.monthStar=b.monthStar and b.ballot <=a.ballot)
------解决方案--------------------
Select * from 表 as t where not exists(
Select * from 表 where monthStar=t.monthStar and ballot> t.ballot)

还有
select * from T as tmp
where not exists(select 1 from T where monthStar=tmp.monthStar and ballot> tmp.ballot)

这2个是一样的,没有区别,就你的题目,应该是符合要求的。
monthStar=tmp.monthStar 月份相同
ballot> tmp.ballot 比最终数据查询里的ballot大的,用not exists保证查询出来的是ballot最大值