從理論上講,您可以爲每個表創建一個不同的表併爲其寫一個視圖。不幸的是,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
感謝您的迴應!理想情況下,我認爲單表繼承最容易實現...雖然我更想知道是否更好地利用資源繼續分解它們,而不是使用一堆PHP if語句篩選每次顯示帖子時都會顯示幾個空條目。或者它會不會很重要? – div 2013-03-10 00:49:19