我只是想知道执行此操作的最佳方法。
我有一个包含 2 个表的数据库。
第一个表
id - primary key
title
第二个表
id - primary key
first_id
order
我想知道插入时确保first_id和order的组合是否存在然后更新其他插入的最佳方法是什么?
例如,如果我尝试将记录插入到第二个表中,first_id = 10 且 order = 1 并且该记录已存在,则更新而不是插入新记录。我在某处读到过有关使列的组合唯一的内容,但不知道如何操作。
编辑:抱歉我忘了提及我正在使用 MySQL
最佳答案
假设sql -server
...
if exists ( select 1 from table2 where id=@id and firstId=@firstid)
begin
update table2 set(...)
end
begin
insert into table2 select ...
end
请确保first_id是table1 id的外键。
关于mysql - SQL 唯一列组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10685242/