1

I have 2 table, first I retrieve all Ids like this:

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:

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

with the colomn2=100 and value = 1

any idea ?

2
  • use a subquery in the second part stackoverflow.com/questions/20232947/… Commented Dec 20, 2013 at 17:32
  • 1
    I think some information is missing here... You select unique entitity_ID's and then insert them into table1... based off of what data? from where? Not sure where the data for this decision comes from. Also "Colomn2" and "value" are terrible names. Commented Dec 20, 2013 at 17:38

2 Answers 2

2

Use a subquery

INSERT INTO table1 ('ENTITY_ID','COLOMN2','VALUE') (select DISTINCT entity_id ,100,1 FROM table2 WHERE column2<>100) 
Sign up to request clarification or add additional context in comments.

2 Comments

it's a good part of solution.. but I guess that we'll do a duplicate entity_id where column2 =100?
no because it's a distinct entity_id. or you can add WHERE column2<>100 to make sure
0

If I'm understanding you correctly, you consider "duplicate" to mean BOTH "ENTITY_ID" and "COLOMN2" have the same value, i.e:

(50, 50) & (50, 99) == not duplicate

(80, 42) & (99, 42) == not duplicate

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

Can you create a compound unique key on your database? Such as, for mysql:

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

You would then need to determine how to handle errors during the insert process.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.