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.
This will work if ID
is unique in Table1
:
INSERT INTO Table2 (ID)
SELECT ID
FROM Table1
WHERE ID = 3;
If ID=3
exists in Table1
you'll get one row inserted. If it doesn't, nothing will be inserted.
If ID
isn't unique in Table1
just add DISTINCT
to the SELECT
:
INSERT INTO Table2 (ID)
SELECT DISTINCT ID
FROM Table1
WHERE ID = 3;
Create a trigger
DELIMITER $$
CREATE
DEFINER = CURRENT_USER
TRIGGER `table2_check` BEFORE INSERT
ON table1
FOR EACH ROW BEGIN
if exists (select id from table1 where id = new.id) then
insert into table2 (id) values (new.id);
end if;
END$$
DELIMITER ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.