Skip to content Skip to sidebar Skip to footer

How To Insert Into Table 1 If Not Exists In Table2?

I am new to mysql. I have a problem in inserting record to table1 if it does not exist in table2.I have 2 tables table1 and table2 in the form: table1 dep_id start stop m

Solution 1:

You can do:

INSERT INTO table1 (start, stop)
SELECT    a.*
FROM      (SELECT123456789 start, 234567890stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE     b.start IS NULL

Where 123456789 and 234567890 are your input values for start and stop respectively.

Then you can check it with rowCount or num_rows_affected based on what DB interface you're using (PDO, mysqli, etc.). If it's 0, then no record was inserted, otherwise, the insert occurred.


SQLFiddle Demo

Solution 2:

I think this is what you want. This takes two values, $start and $stop, and only does the insert if it does not exist in table2:

insertinto table1 (start, stop)
    select*from (select $startasstart, $stop as stop) t
    wherenotexists (select1from table2 wherestart= $startand stop = $end)

Solution 3:

With parameterized values:

INSERT INTO table1 (start, stop)
SELECT    a.*
FROM      (SELECT ? start, ? stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE     b.start IS NULL

This works but we do the insert through SQL statements.

Now, what would be the solution to insert the records by Interface? That is without SQL statement, with the restriction proposed in the problem.

Post a Comment for "How To Insert Into Table 1 If Not Exists In Table2?"