我有兩個不相似的表。只有在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