所以我有两个看起来像这样的表:
New Page Before / After
现在,如果将product_manufacturer插入到makers_tbl中尚不存在的products_tbl中,我想将相应的密钥自动插入Manufacturers_tbl中。
我已经找到了很多有关“级联”插入的一般主题的老文章,但是没有一个人希望集成这样的逻辑。 只能使用mysql吗?还是我必须写一些更多的后端/ php逻辑来完成此任务?
编辑: 如果上述方法不可行,我想知道如何添加外键约束,如果在products_tbl中添加了product_manufacturer,而在Manufacturers_tbl中没有等效的制造商名称,则会引发错误。
答案 0 :(得分:1)
使用触发器很容易,但也很容易获得垃圾。
drop table if exists products_tbl,manufacturers_tbl;
create table products_tbl (product_id int, product_manufacturer varchar(10), product_name varchar(10));
create table manufacturers_tbl (manufacturer_id int, manufacturer_name varchar(10));
drop trigger if exists t;
delimiter $$
create trigger t after insert on products_tbl
for each row
begin
if not exists(select 1 from manufacturers_tbl where manufacturer_name = new.product_manufacturer) then
insert into manufacturers_tbl(manufacturer_name) values (new.product_manufacturer);
end if;
end $$
delimiter ;
insert into products_tbl values
(1,'microsoft','a'),
(2,'msoft','b'),
(3,'mcrosoft','c'),
(4,'microsoft','d');
select * from manufacturers_tbl;
+-----------------+-------------------+
| manufacturer_id | manufacturer_name |
+-----------------+-------------------+
| NULL | microsoft |
| NULL | msoft |
| NULL | mcrosoft |
+-----------------+-------------------+
3 rows in set (0.00 sec)