【问题标题】:weird postgresql query奇怪的postgresql查询
【发布时间】:2016-12-06 14:18:12
【问题描述】:

我无法理解查询,我找到了获取数据的解决方法,但我想知道发生了什么。

所以基本上我想获取不包含在另一个表中的所有 id。如果我分别计算它们,我会得到:

select count(distinct product_sid) 
from gaps_inp.pim_product_channel pc 
where pc.channel_code = 'Amazon' 

计数

200658

然后计算另一张桌子上的项目:

select count(w.sid)
from gaps_fend.product_whitelist w 
where w.channel_code  = 'Amazon'

计数

39697

但现在如果我尝试计算差异:

select count(*) 
from gaps_inp.pim_product_channel pc 
where pc.channel_code = 'Amazon' 
and pc.product_sid not in (
  select w.sid
  from gaps_fend.product_whitelist w 
  where w.channel_code  = 'Amazon'
);

计数

0

gaps_inp.pim_product_channel.product_sidgaps_fend.product_whitelist.sid 两个字段都是 bigint

我可以通过使用 left join其中 sid 为 null 来做到这一点,但我仍然想知道我在 中做错了什么>where not in 查询。

这是解决方法:

select count(distinct pc.product_sid)
from gaps_inp.pim_product_channel pc 
left join gaps_fend.product_whitelist w on w.channel_code = 'Amazon' and pc.product_sid = w.sid
where pc.channel_code = 'Amazon'
and w.sid is null;

计数

160968

【问题讨论】:

    标签: sql postgresql postgresql-9.2


    【解决方案1】:

    我确定下面的查询中有一些 NULL

    select w.sid
    from gaps_fend.product_whitelist w 
    where w.channel_code  = 'Amazon'
    

    NOT INsub-query 返回任何NULL 值时失败,因此您的计数为零。所以解决方法是使用LEFT JOINNOT EXISTS 或在sub-query 中添加IS NOT NULL 条件

    NOT EXISTS 可以处理NULL 值的方法

    SELECT Count(*)
    FROM   gaps_inp.pim_product_channel pc
    WHERE  pc.channel_code = 'Amazon'
           AND NOT EXISTS (SELECT 1
                           FROM   gaps_fend.product_whitelist w
                           WHERE  w.channel_code = 'Amazon'
                                  AND w.sid = pc.product_sid); 
    

    【讨论】:

    • 我回答时错过了你的回答。
    【解决方案2】:

    如果子查询返回 NULL 值,not in 不返回任何行。
    添加and w.sid is not null

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 1970-01-01
      • 2014-04-12
      • 2018-09-01
      • 2012-06-15
      • 2013-09-04
      • 2014-03-17
      • 2010-11-26
      • 2012-09-24
      相关资源
      最近更新 更多