设aa表和bb表有相同的字段num其它不相同,我用
  select * from aa where
     exists(select num from bb t
              where num=t.num
              and code='0371')

select * from aa b,(select num from bb 
                     where code='0371') t
  where b.num=t.num
两个语句查询时,结果会不会相同?能不能说明一下这个语句的执行原理。

解决方案 »

  1.   

    select * from aa  t where
         exists (select num from bb  
                  where num=t.num
                  and code='0371')
      

  2.   

    这样的结果在很大的几率上是不同的。这两个的条件语句不同,
    exists (select num from bb  
                  where num=t.num
                  and code='0371')
    如果这个语句有记录,不论记录数的多少,那么它将返回表中所有的记录数。第二个,则必须匹配条件才行。所以记录数会少与第一个的记录数。
      

  3.   

    如果select num from bb where code='0371'的结果中num不唯一,也就是相同num值出现多次的情况下结果肯定会不一样,exists只要找到匹配的纪录就返回,不会出现重复,而2表关联对重复的纪录会多次关联,例:
    SQL> select id from test_b;ID
    ----------
    001
    002
    004
    005SQL> select user_id,cost from test_a;USER_ID          COST
    ---------- ----------
    001                11
    001               232
    001                23
    001               343
    001               123
    002                12
    002               123
    002                12
    002               213
    002               123
    003              1212
    003               213
    003               12313 rows selectedSQL> 
    SQL> SELECT *
      2  FROM   test_b b
      3  WHERE  EXISTS (SELECT 1
      4          FROM   test_a a
      5          WHERE  a.user_id = b.ID
      6          AND    a.COST > 100)
      7  /ID
    ----------
    001
    002SQL> 
    SQL> SELECT * FROM test_b b,
      2               (SELECT user_id FROM test_a a WHERE COST > 100) t
      3  WHERE b.ID = t.user_id
      4  /ID         USER_ID
    ---------- ----------
    001        001
    001        001
    001        001
    002        002
    002        002
    002        0026 rows selected