0

Imagine an existing table with data (names are self explanatory):

id,name,telephone_1,telephone_2

i want to insert multiple new records with one INSERT (hopefully multiple new records with one insert -if thats a problem i could fall back to insert one-by-one), but i want a new row to be added ONLY if the telephone_1 OR the telephone_2 of the new record does NOT already exist either in telephone_1 OR the telehpone_2 of an existing record.

That means if we have existing data

1, Jimmy, 123, 456

i should not be able to add a

NULL,John,444,123

because John's telephone_2 exists already as telephone_1 of Jimmy.

I'm planning to let mysql do the heavy work instead of my program, but how can i do that? I have done something similar in the past using UNIQUE indexes, but the problem in this case is that the columns are 2. The telephone_1 should not collide with telephone_1 and also should not collide with telephone_2 (and same for telephone_2)

UPDATE-CLARIFICATION: The data i'm trying to insert are not from another table; they are generated on the fly from my program.

2 Answers 2

1

Suppose your table name is contacts, then try to insert record:

INSERT INTO contacts(name,telephone_1,telephone_2)
 SELECT 'John', 444, 123
 FROM contacts
 WHERE telephone_1 NOT IN (444, 123)
 AND telephone_2 NOT IN (444, 123)
 LIMIT 1;

Trick there: if WHERE condition is false then SELECT returns no rows and record is not inserted.

Try here: http://sqlfiddle.com/#!2/5a6e0/1

Sign up to request clarification or add additional context in comments.

1 Comment

@Sharky: small correction added LIMIT 1; to query
0

Try this:

Insert into tableA select * from tableB where tableB.telephone_1 not in (select telephone_1 tableA union select telephone_2 tableA ) AND tableB.telephone_2 not in (select telephone_1 tableA union select telephone_2 tableA )

where

tableA is your main table where you want to insert new record. tableB is other table from where you want to fetch record

5 Comments

there is no TableB, im getting data from my application.
@Sharky You may need to have a temporary table. Or it seems like you need some procedure.
@sri thank you for your answer, are subqueries the only way? is there something more elegant?
@Sharky You need to create temporary table in MySQL when you need to get data from your application. shri is right
@sharky Sub query is fast. You can use join also but I suggest use this sub query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.