简体   繁体   English

MySQL从另一个表插入多个ID

[英]Mysql insert into with multiple id from another table

I have 2 table, first I retrieve all Ids like this: 我有2个表,首先我检索所有ID,如下所示:

select DISTINCT entity_id From table1

I want to create a bulk insert using entity_id and prevent duplicate if the entity_id have a specifique value in the colomn2: 我想使用entity_id创建一个批量插入,并且如果entry_id在colomn2中具有指定值,则防止重复:

example

    *********************************************
    *  ID   *  ENTITY_ID *  COLOMN2 *  value    *
    *********************************************
    *  1    *     230    *    20    *    1      *
    *  2    *     230    *   100    *    1      *
    *  3    *     280    *    20    *    0      *
    *  4    *     220    *    20    *    1      *
    *********************************************
    select DISTINCT entity_id From table1 // return : 230,280,220


    INSERT into table1 ('ENTITY_ID','COLOMN2','VALUE') VALUES([the select id],100,1) 
    WHERE COLOMN2<>100

or something like that? 或类似的东西?

the result need to be: 结果必须是:

creating 2 insert... entity_id=220 and entity_id=280 正在创建2个插入...... entity_id = 220和Entity_id = 280

with the colomn2=100 and value = 1 colomn2 = 100且值= 1

any idea ? 任何想法 ?

Use a subquery 使用子查询

INSERT INTO table1 ('ENTITY_ID','COLOMN2','VALUE')
(select DISTINCT entity_id ,100,1 FROM table2 WHERE column2<>100) 

If I'm understanding you correctly, you consider "duplicate" to mean BOTH "ENTITY_ID" and "COLOMN2" have the same value, ie: 如果我对您的理解正确,那么您认为“重复”是指“ ENTITY_ID”和“ COLOMN2”具有相同的值,即:

(50, 50) & (50, 99) == not duplicate (50,50)&(50,99)==不重复

(80, 42) & (99, 42) == not duplicate (80,42)&(99,42)==不重复

(55, 66) & (55, 66) == duplicate (55,66)&(55,66)==重复

Can you create a compound unique key on your database? 您可以在数据库上创建复合唯一键吗? Such as, for mysql: 如,对于mysql:

CREATE UNIQUE INDEX nodupes ON table1 (ENTITY_ID, COLOMN2);

You would then need to determine how to handle errors during the insert process. 然后,您需要确定在插入过程中如何处理错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM