将数据从一个表插入另一个表会导致重复

时间:2012-04-14 17:04:43

标签: mysql sql

我的table1包含列(id,id_user),table2包含列(id,username)。 用户在table2中注册。所以我想要的是在table2.id中插入table1.id_user新注册用户。

我有这个问题:

INSERT INTO table1 (id_user) SELECT id FROM table2;

但结果是:

例如我在table1.id

 id
 1
 2
 3

当新用户在table2中注册时,table1.id看起来像这样:

id
1
2
3
1
2
3
4

并且每次有新的注册用户时它都会重复所有数据。 如何解决此问题仅添加新注册的用户?

2 个答案:

答案 0 :(得分:1)

INSERT INTO table1  (id_user) 
    SELECT id FROM table2 where id not in (select id_user from table1)

如果使用数据库触发器,则可以自动从table1中的table2插入新用户ID。

答案 1 :(得分:1)

使用max关键字。适用于您的情况。

 " INSERT INTO table1  (id_user) SELECT max id FROM table2"