Polymorphism in SQL database tables?

前端 未结 7 1139
悲&欢浪女
悲&欢浪女 2020-11-27 02:39

I currently have multiple tables in my database which consist of the same \'basic fields\' like:

name character varying(100),
description text,
url character         


        
相关标签:
7条回答
  • 2020-11-27 02:59

    What you are looking for is called 'disjoint subtypes' in the relational world. They are not supported in sql at the language level, but can be more or less implemented on top of sql.

    0 讨论(0)
  • 2020-11-27 03:01

    Since you tagged this PostgreSQL, you could look at http://www.postgresql.org/docs/8.1/static/ddl-inherit.html but beware the caveats.

    0 讨论(0)
  • 2020-11-27 03:10

    Using the disjoint subtype approach suggested by Bill Karwin, how would you do INSERTs and UPDATEs without having to do it in two steps?

    Getting data, I can introduce a View that joins and selects based on specific media_type but AFAIK I cant update or insert into that view because it affects multiple tables (I am talking MS SQL Server here). Can this be done without doing two operations - and without a stored procedure, natually.

    Thanks

    0 讨论(0)
  • 2020-11-27 03:12

    Question is quite old but for modern postresql versions it's also worth considering using json/jsonb/hstore type. For example:

    create table some_table (
        name character varying(100),
        description text,
        url character varying(255),
        additional_data json
    );
    
    0 讨论(0)
  • 2020-11-27 03:18

    Consider using a main basic data table with tables extending off of it with specialized information.

    Ex.

    basic_data
    id int,
    name character varying(100),
    description text,
    url character varying(255)
    
    
    tv_series
    id int,
    BDID int, --foreign key to basic_data
    season,
    episode
    airing
    
    
    movies
    id int,
    BDID int, --foreign key to basic_data
    release_data
    budget
    
    0 讨论(0)
  • 2020-11-27 03:18

    You could create one table with the main fields plus a uid then extension tables with the same uid for each specific case. To query these like separate tables you could create views.

    0 讨论(0)
提交回复
热议问题