Sql 插入不包含';不存在
我有下列表格 临时用户表Sql 插入不包含';不存在,sql,postgresql,database-design,Sql,Postgresql,Database Design,我有下列表格 临时用户表 --------------------------------------- | UserId | LocationID | DepartmentID | --------------------------------------- | 1 | 1 | 1 | | 2 | 2 | 2 | -------------------------------------- 内容来自
---------------------------------------
| UserId | LocationID | DepartmentID |
---------------------------------------
| 1 | 1 | 1 |
| 2 | 2 | 2 |
--------------------------------------
内容来自API
此处的目标是插入这些数据,但它们属于3个不同的表:
用户表
---------------------------------------
| UserId | LocationID | DepartmentID |
---------------------------------------
| 1 | 1 | 1 |
| 2 | 2 | 2 |
--------------------------------------
部门
---------------------------------
| DepId | DepName |
---------------------------------
| 1 | Dep1
| 2 | Dep40
....
| 30 (new)| Dep40 --> New value
----------------------------------
地点
---------------------------------
| LocId | LocName |
---------------------------------
| 1 | Loc1
| 2 | Loc240
....
| 10 (new)| Loc100 --> New value
----------------------------------
基于这个temp_user表,我应该能够添加一个新用户,并插入缺少的部门和位置,以获得类似的结果
例如,考虑到:
- 30是Dep40的id
- 10是Loc100的id
---------------------------------------
| UserId | LocationID | DepartmentID |
---------------------------------------
| 1 | 1 | Dep1 |
| 2 | 2 | Dep40 |
| 3 | 10 | 30 |
--------------------------------------
问题
进行此插入的最佳方式是什么?我可以用一些触发器来完成它,还是应该创建一个存储过程?正确的算法是什么?假设部门名称和地点名称是唯一的,您可以执行以下操作:
-- insert missing locations
insert into location (loc_name)
select location
from temp_users
on conflict (loc_name) do nothing;
-- insert missing departments
insert into department (dep_name)
select department
from temp_users
on conflict (dep_name) do nothing;
-- insert new users
insert into users (id, location_id, department_id)
select tu.user_id, l.id, d.id
from temp_users tu
join location l on l.loc_name = tu.location
join department d on d.dep_name = tu.department
on conflict (id) do nothing; -- ignore existing users with the same ID
以上假设所有id
列都定义为主键,location
和department
的id是使用序列生成的(例如,通过将它们定义为序列
)在location.loc\u name
和department.dep\u name
上定义了唯一的约束
实例:您使用的是MySQL还是Postgresql?不要标记未涉及的产品。我删除了不兼容的数据库标记。请用您实际使用的数据库标记问题。对不起,postgresql currentlyData来自API,它像这样存储在一个临时表中。最好的方法是让其他人来做…我不知道“冲突(..)什么都不做”语句,非常感谢!