【问题标题】:Use SELECT subquery within UNION在 UNION 中使用 SELECT 子查询
【发布时间】:2020-05-08 00:57:49
【问题描述】:

我有两张桌子:

表 1

表 2

我正在尝试使用 UNION(列 ID、日期和金额)编写查询以选择两个表的所有记录。这些表通过 ID 链接。然而,在 UNION 期间选择表 2 中的记录时,如果表 1 中的相关 ID 的 True 或 False 值为 TRUE,我想将表 2 记录的日期更改为表 1 中的日期,最终实现这一点:

这可能吗?

【问题讨论】:

  • 你用的是什么数据库?

标签: sql join subquery inner-join union


【解决方案1】:

如果您的数据库支持,这似乎是一个使用横向连接的方便地方:

select v.*
from table1 t1 join
     table2 t2
     on t1.id = t2.id cross join lateral
     (values (t1.id, (case when t1.true_or_false = 'true' then t2.date else t1.date end), t1.amount),
             (t2.id, t2.date, t2.amount)
     ) v(id, date, amount);

【讨论】:

    【解决方案2】:

    UNION ALL 的第二个查询应该是表的连接:

    select id, date, amount 
    from Table1
    union all
    select 
      t2.id,
      case when t1.trueorfalse = 'TRUE' then t1.date else t2.date end
      t2.amount
    from Table2 t2 inner join Table1 t1
    on t1.id = t2.id
    

    CASE 表达式将返回来自 Table1 或来自 Table2 的日期。
    如果您的数据库支持布尔数据类型,您可能应该使用TRUE 而不是'TRUE'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 2023-03-24
      相关资源
      最近更新 更多