无法让这个查询工作(左外连接)Postgres

Jam*_*mes 4 postgresql

我有这个查询,我想开始工作。我试图在某个非空的日期之后计算外键的所有实例,然后将其与原始表的不同之处连接起来,这样我就可以看到没有条目的变量。这是我的查询:

select fulllist.fk_fc_id 
from 
(
    select distinct fk_fc_id 
    from data_item
) as fulllist 
left outer join
(
    select temp.fk_fc_id, count(*) as number 
    from 
    (
        select * 
        from data_item 
        where di_item_value not like 'Null' 
            and di_timestamp > '2013-11-01 00:00:00'
    )   as temp 
    group by fk_fc_id
)   as lj
    on lj.fc_fk_id=fulllist.fk_fc_id;
Run Code Online (Sandbox Code Playgroud)

错误是

错误:列 lj.fc_fk_id 不存在

第 19 行:在 lj.fc_fk_id=fulllist.fk_fc_id 上;

Tar*_*ryn 8

看起来这只是一个错字。您的子查询正在返回,fk_fc_id但您的连接正在引用fc_fk_id. 似乎您只需要更改查询:

select fulllist.fk_fc_id 
from 
(
    select distinct fk_fc_id 
    from data_item
) as fulllist 
left outer join
(
    select temp.fk_fc_id, count(*) as number 
    from 
    (
        select * 
        from data_item 
        where di_item_value not like 'Null' 
            and di_timestamp > '2013-11-01 00:00:00'
    )   as temp 
    group by fk_fc_id
)   as lj
    on lj.fk_fc_id=fulllist.fk_fc_id;
Run Code Online (Sandbox Code Playgroud)

您似乎还希望将 包含number在最终选择中:

select fulllist.fk_fc_id, coalesce(lj.number, 0) number
from 
(
    select distinct fk_fc_id 
    from data_item
) as fulllist 
left outer join
(
    select temp.fk_fc_id, count(*) as number 
    from 
    (
        select * 
        from data_item 
        where di_item_value not like 'Null' 
            and di_timestamp > '2013-11-01 00:00:00'
    )   as temp 
    group by fk_fc_id
)   as lj
    on lj.fk_fc_id=fulllist.fk_fc_id;
Run Code Online (Sandbox Code Playgroud)


ype*_*eᵀᴹ 5

除了拼写错误(已由@blueefet 发现),您的查询还可以简化:

select fk_fc_id,
       COUNT( CASE WHEN di_item_value not like 'Null' 
                        and di_timestamp > '2013-11-01 00:00:00'
                   THEN 1 ELSE NULL END
            ) AS number 
from data_item 
group by fk_fc_id ;
Run Code Online (Sandbox Code Playgroud)