【问题标题】:SQL Query: How to check for the Join condition in ON clause only if a condition is trueSQL 查询:如何仅在条件为真时检查 ON 子句中的 Join 条件
【发布时间】:2022-01-19 07:59:22
【问题描述】:

我想连接表并获得结果,但我有一个条件,例如,在 ON 子句中,只有在另一个条件为真时才应检查一个连接条件。 例如:

SELECT a.plan_id, a.plan_name, a.sale_s1, b.sale_s1
from (SELECT plan_id, plan_name, sale_s1, sale_s2
     from RESULT_TABLE
      where plan_id = 1245 and sale_id = (any integer value))a
JOIN (SELECT plan_id, plan_name, sale_s1, sale_s2
        from RESULT_TABLE where plan_id = 1245 and sale_id=(any integer value))b
    ON a.plan_id = b.plan_id AND (2nd CONDITION: SHOULD BE CHECKED only if(sale_id=0))

所有列都不为空

请帮我解决这个问题,如何实现第二个条件。

【问题讨论】:

  • sales_id 可以为空吗?
  • 您使用的是哪个 dbms?
  • sale_id 不能为空 @jarlh
  • 我正在使用 postgres @jarlh

标签: sql postgresql


【解决方案1】:

如果 sale_id 不为空:

AND (sale_id <> 0 OR (2nd CONDITION))

【讨论】:

  • 嗨@jarlh 我无法得到这个结果。我收到错误消息:“指定了不明确或不相等的连接条件。考虑使用带有 where 子句的表列表。”
  • 如果您向我们展示您的实际 SQL 查询,它会更容易为您提供帮助! minimal reproducible example 是获得帮助的最佳方式。
猜你喜欢
  • 2018-05-21
  • 1970-01-01
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 2014-02-07
  • 1970-01-01
相关资源
最近更新 更多