左连接问题与哪里AND

时间:2010-06-19 07:54:34

标签: sql sqlite

这是一些硬编码语法。 IPAddr是一个int,这是sqlite,将被移植到mysql。

语法不适用于AND V.IPAddr <> 0。可能是因为V是左连接而可能不存在(null?)。如何在V == null || V.IPAddr <> Val

时取得成功
select Post.id, name, body,
      (select count() from Votes where id=Post.id AND (type & 4)<> 0) as DV
   from Post 
left join Votes as V on V.id=Post.id
   where flag='1'  AND V.IPAddr <> 0 AND DV<1
   limit 1

2 个答案:

答案 0 :(得分:5)

将外部过滤器移动到JOIN状态。否则,过滤器将其更改为INNER JOIN

select Post.id, name, body,
(select count() from Votes where id=Post.id AND (type & 4)<> 0) as DV
from Post 
left join Votes as V on V.id=Post.id AND V.IPAddr <> 0 
where flag='1' AND DV<1
limit 1

答案 1 :(得分:2)

Gbn的解决方案是最好的,但这里有两个其他的解决方案。您可以使用子查询:

from      Post p
left join (
          select  *
          from    Votes
          where   IPAddr <> 0
          ) v
on        v.id = p.id

或改进的where子句:

from      Post p
left join Votes v
on        v.id = p.id
where     (IPAddr <> 0 or IPAddr is null)