【问题标题】:Postgres, Join table under certain conditionPostgres,特定条件下的连接表
【发布时间】:2022-08-16 23:46:02
【问题描述】:

我需要写一个查询,返回\'prospect\'信息,以及相关的\'unit\'信息(如果有的话)。但是我面临一个无法解决的困难:表前景中的unit_desire列可能为空值,这使得结果整体返回空值。我需要的是如果 unit_desire 为空,则只返回潜在客户信息。如果 unit_desire 不为空,则返回两部分信息。我该如何解决这个问题?

SELECT prospect.*, unit.*
FROM prospect
LEFT unit
ON (prospect.unit_desired=unit.name) 
WHERE prospect.id=\'100000057\'

    标签: postgresql


    【解决方案1】:

    几乎你需要一个 if - 在第一种情况下,返回两个表中的所有列,否则只返回潜在表中的列。

    在 SQL 中,我们可以利用只有一种情况会返回结果(unit_desired 为 null 或不是)......所以我们可以将两种情况的结果联合起来:

    SELECT prospect.*, unit.*
    FROM prospect
    LEFT unit
    ON (prospect.unit_desired=unit.name) 
    WHERE prospect.id='100000057' AND prospect.unit_desired is not null
    
    UNION ALL
    
    SELECT prospect.*
    FROM prospect
    WHERE prospect.id='100000057' AND prospect.unit_desired is null
    

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      相关资源
      最近更新 更多