第一个sql:
select count(*)
  from t_baidu_p_units u
  left outer join t_baidu_p_plans p on u.p_plan_id = p.id
                                     and p.id = 3176
 where p.id is null
 order by u.p_plan_id desc
结果:5032
如果把“where p.id is null”注释掉结果是:5271
在t_baidu_p_plans中,id没有为null的
对这个结果不理解,求教下

解决方案 »

  1.   

    当在t_baidu_p_plans中找不到对应记录时,则返回一个t_baidu_p_plans部分为空的记录。
      

  2.   

    你是左边接   有可能会出现null值的时候要是inner join 就不同了
      

  3.   

    改为这样:
    select u.id,u.p_plan_id,u.unit_name,p.id,p.plan_name
      from t_baidu_p_units u
      left outer join t_baidu_p_plans p on u.p_plan_id = p.id
                                         and p.id = 3176
     where p.id is null
     order by u.p_plan_id desc
    查询的结果中“p.id,p.plan_name”都为空,但是结果中没有p.id=3176的列
      

  4.   

    总之,在where中如果有与t_baidu_p_plans相关的字段条件时,总是会出现不能理解的结果
      

  5.   

    这个结果是正常的。而且并非都为空,从你上面的统计数据上看,5271条记录中有239条的不为空。这是因为使用了left outer join,不符合关联条件的,右边的显示为空。
    将left outer join改成inner join或将and p.id=3176移到where下看看
      

  6.   

    可以看看外连接的介绍
    join on后面的是关联条件
    where里的是过滤条件
      

  7.   

    结果却是是这样的,查询的结果中“p.id,p.plan_name”都为空,并且没有出现那239不为空的数据,但是如果改为“where 1=1”,就会出现那239条数据。平时没有这么写过sql,突然发现把链接查询的条件放入到where中,就会出现这种情况,查了下链接查询的资料,不理解啊~~
      

  8.   

    谢谢各位,问题解决了,终于明白了,首先根据left outer join的条件,查询出结果集,然后在where中过滤。当用where 1=1时,对结果集没有影响,但是用p.id is null时,会在结果集中过滤掉p.id为不为null的结果,就出现了以上结果,即将239条p.id不为空的过滤掉