I have 2 tables that are not similar. Is there some way by which I can insert a record into table2
only if a record with a similar value was found in table1
? I'm doing all this with php pdo
and mysql
For Example:
Lets say table1
has values like:
id
--
1
2
3
4
6
Then:
insert into table2 (id) values (3) // Will work, because id 3 exists in table1
insert into table2 (id) values (7) // Will not work, because id 7 does not exists in table1
Right now, the way I do this is to run a select count(id) where id = 3
and then if a id
exists, it'll be inserted. Cumbersome!
Is there a way to do this without having to first do a select
and then an insert
?
Since this is just the beginning, I'm willing to make changes if something like a foreign key
etc. needs to be added.
The only query being run here is insert into table2 (id) values (3)
. And that needs to work only if id = 3
is found in table1
. The value 3
is user supplied.