理论上,您可以为每个表创建一个不同的表并在其上编写一个视图。不幸的是,MySQL 不支持您需要插入的触发器而不是触发器。这是一个使用 sqlite3 的示例。
create table PhotoTable (
id integer not null PRIMARY KEY AUTOINCREMENT,
PhotoName varchar(255),
Camera varchar(255)
);
create table StaffTable (
id integer not null PRIMARY KEY AUTOINCREMENT,
StaffName varchar(255)
);
--- Odd way of seeding AUTOINCREMENT value in SQLite3
insert into StaffTable(StaffName) values('odd');
delete from StaffTable;
update SQLITE_SEQUENCE set seq = 100000 where name ='StaffTable';
create view posts as
select id, 'Photo' as Type, PhotoName, Camera, NULL as StaffName from PhotoTable
union all
select id, 'Staff' as Type, NULL as PhotoName, NULL as Camera,StaffName from StaffTable;
create trigger postsinsert
instead of insert on posts
for each row
begin
insert into PhotoTable(PhotoName, Camera) select new.PhotoName, new.Camera where New.Type ='Photo';
insert into StaffTable(StaffName) select new.StaffName where New.Type = 'Staff';
end;
insert into posts(Type, PhotoName, Camera) values('Photo','photo1','nk');
insert into posts(Type, PhotoName, Camera) values('Photo','photo2','canon');
insert into posts(Type, StaffName) values('Staff', 'spaceghost');
你得到预期的结果
select * from posts;
1|Photo|photo1|nk|
2|Photo|photo2|canon|
100001|Staff|||spaceghost