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 modified deleted
1 23456789 167921525 Yes No
2 34567812 345678145 Yes No
3 32789054 327890546 No No
table2
start stop modified deleted
23456789 167921525 No No
34567823 345678145 No No
32789053 727890546 No No
I am trying to insert values into table1’s start and stop field values only if it does not exist in table2’s “start” and “stop” columns. If it exists the I need to throw an error.
These tables do not have a primary key foreign key relationship.
I apologize for not knowing correct syntax but I have to do something like this in mysql and PHP.
Replace Into into table1 set 'start'=> $start,'stop' => $stop
(select 'start','stop' from table2 where table1.start and table1.stop not in table2.start and table2.stop);
How do I query these 2 tables to check if Table1.start and Table1.stop fields do not match with Table2.start and Table2.stop before inserting to table1?
You can do:
Where
123456789and234567890are your input values forstartandstoprespectively.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