2011-12-19 117 views
0

我很困惑,为什么Postgresql定位函数为什么看起来是一个简单的测试给出了不同的结果。为什么Postgres position()函数会给出不同的结果?

这里查询#1:

SELECT count(*) 
FROM 
    dnasample D, ibg_studies ST, subjects S 
WHERE 
    D.studyindex=ST.studyindex 
    AND ST.studyabrv='CONGER' 
    AND D.subjectidkey=S.id 
    AND D.projectindex IS NULL 
    AND POSITION('Previous subjectid:' in D.comment) IS NULL 

返回的246

然后在这里一个结果是查询#2:

SELECT count(*) 
FROM 
    dnasample D, ibg_studies ST, subjects S 
WHERE 
    D.studyindex=ST.studyindex 
    AND ST.studyabrv='CONGER' 
    AND D.subjectidkey=S.id 
    AND D.projectindex IS NULL 
    AND POSITION('Previous subjectid:' in D.comment)=0 

我不明白为什么这回这样的不同的结果?

我试着读Postgres的文件,以澄清区别零和空字符串,但没有多少运气还存在之间...

由于提前, --Rick

回答

5

position(needle in haystack)函数将返回:

  • 零,如果needle不为NULL,而不是在haystackhaystack不为NULL。
  • 如果needlehaystack中为正值,其中一个为haystack的开头。
  • NULL如果needlehaystack为NULL。

例如:

=> select position('a' in 'a') as a, 
      position('a' in 'b') as b, 
      position('a' in null) as n1, 
      position(null in 'a') as n2, 
      position(null in null) as n3; 
a | b | n1 | n2 | n3 
---+---+----+----+---- 
1 | 0 | | | 

n1下空斑通过n3是NULL值。

所以这个条件:

POSITION('Previous subjectid:' in D.comment) IS NULL 

等同于:

D.comment IS NULL 

,而这一点:

POSITION('Previous subjectid:' in D.comment)=0 

为真当且仅当D.comment IS NOT NULLD.comment不含'Previous subjectid:'

所以这两个条件是完全不同的。

+0

谢谢;我明白现在的差异;很好的答案。 – rixter 2011-12-20 23:14:16

+0

已回答此问题...不再需要! – rixter 2011-12-20 23:15:29

1

是NULL实际上一个没有价值。 0是一个位数据池。

这是区别。

+0

谢谢;这有助于... – rixter 2011-12-19 23:03:40

相关问题