代码之家  ›  专栏  ›  技术社区  ›  quantum_well

有条件地从一个表插入到另一个表中

  •  0
  • quantum_well  · 技术社区  · 6 年前

    同一名称可能出现在 表1 . 我想按顺序1,2,…一种方法是

    1. 使用创建新表 name 作为主键和 id 作为 serial 类型。
    2. 选择 名称 table1 把它插入 table2 只有当它不存在的时候
    table1 (name vchar(50), ...)
    
    table2 (name vchar(50) primary key, id serial)
    
    
    insert into table2(name)
    select name
    from table1 limit 9
    where not exists (select name from table2 where name = table1.name)
    

    这不管用。怎么解决?

    1 回复  |  直到 6 年前
        1
  •  0
  •   a_horse_with_no_name    6 年前

    只需选择不同的值:

    insert into table2(name)
    select distinct name
    from table1
    order by name;