SQL: multi valued attributes

后端 未结 4 1184
庸人自扰
庸人自扰 2020-12-31 04:21

I created a table that contains information about a company. One attribute is their telephone number. A company can have many telephone numbers.

How do I create mul

4条回答
  •  耶瑟儿~
    2020-12-31 04:58

    There're some possibilities in different implementations of RDBMS.

    For example, in PostgreSQL you can use array or hstore or even JSON (in 9.3 version):

    create table Company1 (name text, phones text[]);
    
    insert into Company1
    select 'Financial Company', array['111-222-3333', '555-444-7777'] union all
    select 'School', array['444-999-2222', '555-222-1111'];
    
    select name, unnest(phones) from Company1;
    
    create table Company2 (name text, phones hstore);
    
    insert into Company2
    select 'Financial Company', 'mobile=>555-444-7777, fax=>111-222-3333'::hstore union all
    select 'School', 'mobile=>444-999-2222, fax=>555-222-1111'::hstore;
    
    select name, skeys(phones), svals(phones) from Company2    
    

    sql fiddle demo

    You can also create indexes on these fields - https://dba.stackexchange.com/questions/45820/how-to-properly-index-hstore-tags-column-to-faster-search-for-keys, Can PostgreSQL index array columns?

    In SQL Server, you can use xml datatype to store multivalues:

    create table Company (name nvarchar(128), phones xml);
    
    insert into Company
    select 'Financial Company', '555-444-7777111-222-3333' union all
    select 'School', '444-999-2222555-222-1111'
    
    select
        c.name,
        p.p.value('@type', 'nvarchar(max)') as type,
        p.p.value('.', 'nvarchar(max)') as phone
    from Company as c
        outer apply c.phones.nodes('phone') as p(p)
    

    sql fiddle demo

    You can also create xml indexes on xml type column.

提交回复
热议问题