sql - 仅当 2 个或更多列匹配时才选择 - postgresql

标签 sql postgresql

我正在自学 SQL,对编码还很陌生。 我需要有关我正在编写的脚本的帮助,该脚本从几个表中选择数据以将其插入到另一个已有数据的表中。 但是,如果 4 列中的 2 列不匹配,我只想将数据插入第二个表。

这是我插入之前选择的数据示例(table1):

warehouse   │  section    │   division   │  division_code

  1       │   10   │   1     │   BOXES
  1       │   11   │   1     │   CRATES
  1       │   12   │   1     │   LANES
  2       │   3    │   1     │   OFFICE

这是我要插入到(table2)中的表中数据的示例:

warehouse   │  section    │   division   │  division_code

  1       │   1    │   1     │   BOXES
  1       │   2    │   1     │   LANES
  1       │   3    │   1     │   FUSES
  1       │   4    │   1     │   OFFICE
  2       │   1    │   1     │   LANES
  2       │   2    │   1     │   CRATES

我只想将表 1 中的行插入表 2,其中 warehouse 和 division_code 列的组合不存在。案例中的两行是:

  1       │   11   │   1     │   CRATES
  2       │   3    │   1     │   OFFICE

我尝试使用 EXCEPT,但这不起作用,因为部分列不同,并且我不确定在这种情况下如何使用 NOT IN 或 NOT EXISTS,因为需要检查 2 列。

非常感谢任何帮助! 谢谢!

最佳答案

SQL 的一个好处是您可以用几乎相同的方式使用它来表达您的需求。

I only want to insert the rows from table 1 into table 2 where the combination of warehouse and division_code columns doesn't exits.

-- I only want to insert the rows from table 1 into table 2 ...
insert into table2
select * from table1
-- where ... doesn't exits
where not exists (
  select 1 
  from table2
  -- the combination of warehouse and division_code columns
  where
    table2.warehouse = table1.warehouse and
    table2.division_code = table1.division_code)

在 PostgreSQL 中,您可以使用行语法以更方便的方式完成此操作:

insert into table2
select * from table1
where (table1.warehouse, table1.division_code) not in (
  select table2.warehouse, table2.division_code from table2)

关于sql - 仅当 2 个或更多列匹配时才选择 - postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52432472/

相关文章:

sql - 批量插入分区表和表级锁

sql - 在SQL中使用计数器值计算行之间的差异

mysql - 多列索引中主键的优先级?

ruby-on-rails - 角色未添加到数据库中的用户

postgresql - Squeryl 中的显式 jsonb 类型转换

python - psycopg2.OperationalError : could not translate host name "xxxxxx.us-east-1.rds.amazonaws.com" to address: Unknown host

php - mysql:合并两个彼此无关的表?

mysql - PostgreSQL:有效的变量分配示例?

sql - 是否有可能(如何?)从 "after update"触发器返回旧值

php - Yii CDbCriteria 将 2 个属性与单个值进行比较