【问题标题】:Postgresql SQL Select items from table1 based on a condition from table2Postgresql SQL 根据表 2 中的条件从表 1 中选择项目
【发布时间】:2018-12-20 00:56:34
【问题描述】:

我正在尝试从 table1 中选择具有子 table2 的项目,其中涉及第三个 table3。

Select j.ccmasterid, 
(Select sum(i.ccmatpullqty) From table2 i 
 Where i.ccmasterid = j.ccmasterid)  pulled
 from table1 j
INNER JOIN table3 s on j.ccstatus = s.sysstatusid and s.ccopenjob=false
where j.ccmasterid LIKE 'W%' and pulled = 0  

这会产生一个错误:

错误:“拉”列不存在 第 6 行:其中 j.ccmasterid LIKE 'W%' 和 pull = 0

如果我从查询中取出“and pull = 0”,它的工作原理就像人们期望从 table1 中生成一个记录列表一样,其中 table2 中的值的总和被拉取。

ccmasterid    pulled
W106063            0
W100553            9
W100685            1

我不知道如何根据拉为 0 进行选择。

【问题讨论】:

    标签: sql postgresql conditional


    【解决方案1】:

    将此查询更改为子查询,并将 WHERE 条件移至外部查询:

    SELECT * FROM (
       Select j.ccmasterid, 
       (Select sum(i.ccmatpullqty) From table2 i 
        Where i.ccmasterid = j.ccmasterid)  pulled
        from table1 j
       INNER JOIN table3 s on j.ccstatus = s.sysstatusid and s.ccopenjob=false
       where j.ccmasterid LIKE 'W%'
    ) x
    WHERE  pulled = 0  
    

    【讨论】:

    • 谢谢。就是这样。
    【解决方案2】:

    如果使用GROUP BY 子句加入聚合查询,则避免在外部查询中为每一 行而不是一次 运行相关子查询:

    SELECT j.ccmasterid
    FROM table1 j
    INNER JOIN table3 s 
        ON j.ccstatus = s.sysstatusid AND s.ccopenjob = false
    INNER JOIN
       (SELECT i.ccmasterid, SUM(i.ccmatpullqty) AS pulled
        FROM table2 i 
        GROUP BY i.ccmasterid
       ) AS agg
        ON agg.ccmasterid = j.ccmasterid
    WHERE j.ccmasterid LIKE 'W%' AND agg.pulled = 0  
    

    甚至使用 CTE

    WITH agg AS
        (SELECT i.ccmasterid, SUM(i.ccmatpullqty) AS pulled
         FROM table2 i 
         GROUP BY i.ccmasterid)
    
    SELECT j.ccmasterid
    FROM table1 j
    INNER JOIN table3 s 
        ON j.ccstatus = s.sysstatusid AND s.ccopenjob = false
    INNER JOIN agg
        ON agg.ccmasterid = j.ccmasterid
    WHERE j.ccmasterid LIKE 'W%' AND agg.pulled = 0  
    

    【讨论】:

      猜你喜欢
      • 2016-06-13
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多