星期二, 十一月 25, 2008

in\exists子查询的区别和联系

in查询:(left expression)in (select_sub_expression )

exists 查询:(left expression)exists (select_sub_expression )

  两种方式的执行过程有些差别。执行EXISTS子查询,数据库系统会首先检查主查询,然后运行子查询 直到它找到第一个匹配项。执行IN子查询,首先执行子查询,并将获得的结果列表存放在在一个加了索引的临时表中。在执行子查询之前,系统先将主查询挂起, 待子查询执行完毕,存放在临时表中以后再执行主查询。

还是昨天的例子
有3个表:
s:学生表;
c:课程表;
sc:选课表

--查询一个sid为002的学生没有选的课程,用in查询的语句是:
1):select * from c where c.cid not in (select sc.cid from sc where s.sid='002')
--等价于下面的exsits语句
2):select * from c where not exists (select sc.cid from sc where s.sid='002' and c.cid = sc.cid)

语句1先执行子查询,即先把所有002学生选的课程的ID查出来了,然后执行主查询,看看哪些课程的ID不在子查询的结果集中。
语句2先执行主查询,即先把所有的课程查出来,然后再遍历结果集,看看not exists是不是true。找到满足c.cid <> sc.cid(因为exists前有一个not)的条件时,便输出。

考虑下面的查询:
--选修了所有课程的学生==不存在一门课,该学生没有选
select sname from s where not exists(
select * from c where c.cid not in (select cid from sc where sc.sid = s.sid))

==
select sname from s where not exists(
select * from c where not exsits (select cid from sc where sc.sid = s.sid and c.cid = sc.sid))

星期一, 十一月 24, 2008

python中类的静态方法(方法修饰符)

python中除了最常用类实例方法外,还有类方法和静态方法两种。
##############################
#类方法
##############################
class Foo:
        str = "I'm a static method."

        @classmethod     #方法修饰符――指明该方法为类方法
        def bar(cls):         #cls为类对象,可以通过他引用静态数据成员
            print cls.str
           
Foo.bar()                      #静态方法的调用方法一:类对象.方法名()
o1 = Foo()
o1.bar()                        #静态方法的调用方法二:类实例对象.方法名()

##############################
#静态方法
##############################
class Foo:
        str = "I'm a static method."

        @staticmethod
        def bar():                        #没有cls参数
            print Foo.str
           
Foo.bar()
o1 = Foo()
o1.bar()

更多见

Python类的基础入门知识