我有以下表格
项目表
PROJECT_ID,PROJECT_NAME
技能表
skill_id也,skill_name
project_skill表(多对多关系)
project_skill_id,PROJECT_ID,skill_id也
浏览器将有一个表单,要求用户输入项目名称和标签的SO样式自动完成功能。我将以下json格式发送回sql进行插入
{"project_name":"foo","skills":["bar","baz"]}
我的问题涉及用户编辑现有项目的情况。假设用户删除了" baz"从技能和包括" zed"。我如何正确处理更新多对多表
{"project_name":"foo","skills":["bar","zed","biz"]}
这也适用于修改project_name等。我是否检查修改内容并更新必要或执行完整删除并插入
答案 0 :(得分:0)
我使用带有MERGE的CTE(注意这是SQL Server但Postgres应该类似):
;WITH src AS
(
SELECT p.project_id, s.skill_id
FROM
dbo.project AS p
INNER JOIN @input AS i ON p.project_name = i.project_name
INNER JOIN dbo.skill AS s ON i.skill_name = s.skill_name
)
MERGE INTO dbo.project_skill AS tgt
USING src
ON tgt.project_id = src.project_id AND tgt.skill_id = src.skill_id
WHEN NOT MATCHED BY TARGET THEN
INSERT (project_id, skill_id) VALUES (src.project_id, src.skill_id)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
其中@input包含新值:
DECLARE @input TABLE
(
project_name VARCHAR(100),
skill_name VARCHAR(100)
);