请问这2个语句的查询结果为什么不一样

SELECT count(*) from e where not exists(select 1 from p where url=e.url) and exists(select 1 from p where name=e.name)

SELECT count(*) from e,p where e.url<>p.url and e.name=p.name

我感觉没有什么本质区别,谁能帮我分析一下?

作者: zhengdows   发布时间: 2011-06-13


count(*) where e.url<>p.url 不等于总数减去 count(*) where e.url=p.url
楼主三思。

作者: zy112429   发布时间: 2011-06-13

应该是有null的缘故。

= 和 <> 都判断不了null
判断null需要 is 或是 is not

作者: maco_wang   发布时间: 2011-06-13

可我的两个表中的name和url都没有null值,应该相等吧?

作者: zhengdows   发布时间: 2011-06-13

如果出现null值的话就不一样了

作者: fredrickhu   发布时间: 2011-06-13

例如表

e

url ------- name
-----------------
 1 ---------- a
 1 ---------- b

p

url ------- name
-----------------
 1 ---------- a
 2 ---------- b



1、SELECT count(*) from e where not exists(select 1 from p where url=e.url) and exists(select 1 from p where name=e.name)

2、SELECT count(*) from e,p where e.url<>p.url and e.name=p.name

对于1 结果是0  
对于2 结果是1

分析:对于1,not exists只要有不符合的记录都会被略去,例如上边e表url为1的记录,在统计count的时候会把url为1的所有记录略过,和2不同。

作者: AcHerat   发布时间: 2011-06-13

引用 3 楼 zhengdows 的回复:
可我的两个表中的name和url都没有null值,应该相等吧?
完全不相等,为什么自己不试试呢。

作者: zy112429   发布时间: 2011-06-13

SQL code
select * from e where name is null or url is null
select * from p where name is null or url is null

确定没有数据?

作者: maco_wang   发布时间: 2011-06-13

引用楼主 zhengdows 的回复:
SELECT count(*) from e where not exists(select 1 from p where url=e.url) and exists(select 1 from p where name=e.name)

SELECT count(*) from e,p where e.url<>p.url and e.name=p.name

我感觉没有什么本质区别,谁……

我怎么觉得就千差万别呢?

第一条语句:SELECT count(*) from e where not exists(select 1 from p where url=e.url) and exists(select 1 from p where name=e.name)
如果条件满足就相当于True,即SELECT count(*) from e where 1 = 1,返回值为表中的所有记录数
如果条件不满足就相当于False,即SELECT count(*) from e where 1 <> 1,返回值为0

第二条语句:SELECT count(*) from e,p where e.url<>p.url and e.name=p.name
如果e.url<>p.url and e.name=p.name条件成立就会统计出符合这个条件的记录数,
如果e.url<>p.url and e.name=p.name条件不成立就返回0.

作者: Lyongt   发布时间: 2011-06-13

引用 5 楼 acherat 的回复:
例如表

e

url ------- name
-----------------
1 ---------- a
1 ---------- b

p

url ------- name
-----------------
1 ---------- a
2 ---------- b



1、SELECT count(*) from e where no……

作者: jiangsuwx   发布时间: 2011-06-13


不一样的,一般来说第二种会大于第一种,
如:e中一个name值和p中多个name的值是一样的情况下,
或p中一个name值和e中多个name的值是一样的情况下

作者: cd731107   发布时间: 2011-06-13

第一个语句,FROM 语句只用到了e表.所以你的结果肯定不会超过e表的数量.
第一个语句,FROM 语句用到了e表和p表.如果e,p是不是1对1,结果肯定会比第一个语句要大.

引用楼主 zhengdows 的回复:
SELECT count(*) from e where not exists(select 1 from p where url=e.url) and exists(select 1 from p where name=e.name)

SELECT count(*) from e,p where e.url<>p.url and e.name=p.name

我感觉没有什么本质区别,谁……

作者: xiaoliaoyun   发布时间: 2011-06-13