【问题标题】:inserting into a table records from another table with a condition使用条件从另一个表中插入表记录
【发布时间】:2020-06-04 12:03:56
【问题描述】:

假设我有两个表 t1 和 t2。

  • t1 有两个整数 col1 (primary) 和 col2
  • t2 有两个 cols 一个外键 t1.col1 和 t2.col2

我想做以下事情

  1. 仅检索 t1.col2 唯一或 t1.col2 重复的记录,仅检索 t2.col2 不为空的记录。

  2. 将以上记录插入另一个汇总表,比如说t3

这是我尝试过的:

insert into t3 (col1,col2) 
    select col1, col2 
    from t1 
    where t.col1 in (select A.col1 from t1 as A 
                     group by 1 
                     having count(*) > 1
    union
    select col1, col2 
    from t1, t2 
    where t.col1 in (select A.col1 from t1 as A  
                     group by 1 
                     having count(*) > 1
      and t2.col2 is not null;

虽然 'union qry' 独立工作,但插入不会发生。

请有任何想法或任何其他有效的方法来实现这一点

【问题讨论】:

  • 请提供样本数据、所需结果和适当的数据库标签。
  • 您的子查询 bothhaving count(*) > 1 子句之后缺少右括号 ) .... - 以及您的后半部分 @ 987654325@ 产生笛卡尔交叉连接,因为您在 from 子句中指定了两个表 - 逗号分隔 - 而不是两个表之间的 JOIN 条件.....
  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(25 多年前),不鼓励使用它

标签: sql


【解决方案1】:

您可以选择要使用的记录:

select t1.*
from (select t1.*, count(*) over (partition by col2) as cnt
      from t1
     ) t1 
where cnt = 1 or
      exists (select 1 from t2.col1 = t1.col1 and t2.col2 is null);

剩下的只是一个insert

【讨论】:

  • 感谢问题是 union qry 正在独立工作(我不小心遗漏了连接条件),问题是要插入这个,如果在喂一个时需要任何特殊的“处理”从联合到 INSERT 的结果集?
猜你喜欢
  • 2017-08-01
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 2023-02-04
  • 1970-01-01
相关资源
最近更新 更多