这是我的mysql查询:
INSERT INTO TEACHER (FACULTYID,FIRST_NAME,SURNAME)
VALUES('17427', 'fn', 'ls')
ON DUPLICATE KEY UPDATE TEACHERID = TEACHERID,
FACULTYID = FACULTYID,
FIRST_NAME = 'fn',
SURNAME = 'ls'
WHERE FIRST_NAME = 'fn'
AND SURNAME = 'ln'
我想仅在名字和姓氏的组合匹配时更新值。我怎么能这样做?
例如, 如果我的表格中有以下行
TeacherID = primary key
FACULTYID = foreign key
FIRST_NAME = unique
SURNAME = unique
TeacherID, FACULTYID, FIRST_NAME, SURNAME
6678 17427 Makram Bou Nassar
我来到同一位老师的另一个实例
FIRST_NAME = Makram, SURNAME = Bou Nassar.
然后我想中止添加新元组,只保留旧元组。
假设我和老师一起来了
FIRST_NAME = Makram, SURNAME = OBAJI
then I add a new tuple.
Also add a new tuple when
FIRST_NAME = Ali, SURNAME = Bou Nassar
答案 0 :(得分:2)
您需要一个唯一索引来识别重复项。 where
没有on duplicate key
条款。所以:
CREATE UNIQUE INDEX unq_teacher_firstname_surname on teacher(first_name, surname);
注意:您也可以使用唯一约束执行此操作(使用唯一索引实现唯一约束)。
然后:
INSERT INTO TEACHER (FACULTYID, FIRST_NAME, SURNAME)
VALUES('17427', 'fn', 'ls')
ON DUPLICATE KEY UPDATE FACULTYID = VALUES(FACULTYID);
注意:
first_name
和surname
,因为它们已经相同。teacherid
,因为它未在输入时提供。VALUES(FACULTYID)
返回为该列提供的值。答案 1 :(得分:0)
使用更新表。例如。
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;