我有两个不相似的表。只有在table1
中找到具有类似值的记录时,我才能通过某种方法将记录插入table2
?我做这一切都是php pdo
和mysql
仅当表1中存在类似记录时才插入表2.
例如: 比方说table1
有类似的值:
id
--
1
2
3
4
6
然后:
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
眼下,方式我这样做是运行一个select count(id) where id = 3
,然后如果id
存在,它会被插入。繁琐!
有没有办法做到这一点,而不必先做select
,然后insert
?
由于这仅仅是个开始,如果需要添加诸如foreign key
等等,我愿意进行更改。
这里运行的唯一查询是insert into table2 (id) values (3)
。而且只有在table1
中找到id = 3
时,该功能才有效。值为3
是用户提供的。
http://stackoverflow.com/questions/5907206/mysql-insert-into-tbl-select-from-another -table-and-some-default-values – Nils
这是完全不同的。我试图在table2中插入一个值,只有当table1中存在具有该id值的行时。不从table1中选择到表2 – Norman