如何通过比较多列来更新mysql记录

时间:2017-03-22 14:12:24

标签: php mysql

实际上我需要在将两个mysql表与多列进行比较时更新mysql记录,如果记录不存在,则应该作为新记录插入。我怎样才能实现它?这是我的情景如下。提前致谢

表1:

Name   | Age   | occupation    | DOJ    | Salary   |
----------------------------------------------------------------
Raju  | 27 | Manager | 12/12/12 | 12,000
--------------------------------------
Raman  | 30 | Director | 11/11/11 | 14,000
-
Sriram  | 25 | Assistant | 10/10/10 | 10,000
-

表2:

Name   | Age   | occupation    | DOJ    | Salary   |
----------------------------------------------------------------
Raju  | 27 | Manager | 12/12/12 | 12,000
--------------------------------------
Raman  | 30 | Director | 8/8/8 | 18,000
-
Ravi  | 34 | CEO | 9/9/9 | 30,000
-

我有一堆带有上述结构的记录,我需要在临时表(temp_table)中上传记录,然后将该表与Main表(main_table)进行比较,是否有任何记录存在,如果存在任何更新,需要在Main_table上进行更新,否则在main_table中将其作为新更新插入。

谢谢。

1 个答案:

答案 0 :(得分:1)

当且仅当给定的Name存在时,您可以编写一个返回1的选择。然后你可以使用它作为另一个选择的子查询,它将否定存在,找到应该插入的内容。最后,您可以对insert - select使用第二个选择:

insert into Table2(Name, Age, Occupation, Doj, Salary)
select Name, Age, Occupation, Doj, Salary
from Table1 t2 where not exists (select 1
                              from Table2 t
                              where t.Name = t2.Name)