在mysql中插入和更新

时间:2014-07-16 11:02:39

标签: mysql sql

这里我必须按如下方式更新表格,

我的表格如下,

| subject | Type | Gender | s1 | s2 | s3 | s4 | s5 | s6 |
| sub1    | 1    |  M     | 10 | 20 | 0  | 0  | 0  | 0  |
| sub1    | 1    |  F     | 11 | 22 | 0  | 0  | 0  | 0  |
| sub1    | 2    |  M     | 30 | 40 | 0  | 0  | 0  | 0  |
| sub2    | 1    |  M     | 50 | 60 | 0  | 0  | 0  | 0  |
    .
    .
    .
| subn    | 2    |  F     | 500 | 600 | 0  | 0  | 0  | 0  |

这里我有另一张表2,

| subject | Type | Gender | s1| s2| s3 | s4  | s5 | s6 |
| sub1    | 1    |  M     | 0 | 0 | 11 | 16  | 25 | 30 |
| sub1    | 1    |  F     | 0 | 0 | 12 | 17  | 24 | 29 |
| sub1    | 2    |  M     | 0 | 0 | 13 | 18  | 23 | 28 |
| sub1    | 2    |  F     | 0 | 0 | 14 | 19  | 22 | 27 |
| sub2    | 1    |  M     | 0 | 0 | 15 | 20  | 21 | 26 |
   .
    .
    .
| subn    | 2    |  F     | 0 | 0 | 50  | 60 | 70 | 80 |

我需要更新表2中表1中的值。不要查看它的样本值。注意:两个表中的额外行可能更少或更多。如果表1中的行无效,则必须在表2中的表1中识别并插入该行。如果您需要有关于此的任何疑问,我就在这里。提前谢谢。

2 个答案:

答案 0 :(得分:4)

您想使用insert . . . on duplicate key update。首先,您需要一个唯一的键来定义重复项。我假设它是前三列:

create unique index idx_table_subject_type_gender on table(subject, type, gender);

然后你可以做你想做的事情:

insert into table1(subject, type, gender, s1, s2, s3, s4, s5, s6)
    select subject, type, gender, s1, s2, s3, s4, s5, s6
    from table2 t2
    on duplicate key update s1 = t2.s1, s2 = t2.s2, s3 = t2.s3, s4 = t2.s4, s5 = t2.s5, s6 = t2.s6;

答案 1 :(得分:2)

更新:

UPDATE table1
JOIN table2 ON table1.subject = table2.subject AND 
               table1.type = table2.type AND 
               table1.gender = table2.gender
SET table1.s1 = table2.s1, table1.s2 = table2.s2, 
    table1.s3 = table2.s3, table1.s4 = table2.s4, 
    table1.s5 = table2.s5, table1.s6= table2.s6

用于插入table1中不存在的行:

INSERT INTO table1
SELECT *
FROM table2
WHERE (subject, type, gender) NOT IN (
   SELECT subject, type, gender
   FROM table1
)