Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Devo colocar valores EAV em uma tabela de tipo de dados?


Francamente, a melhor opção é "não EAV". Procure usar hstore campos, XML , ou json .

No PostgreSQL não há vantagem de desempenho em usar tabelas por tipo de dados. NULL os valores são armazenados em um NULL compacto bitmap, então faz pouca diferença se você tem uma tupla como (NULL, NULL, NULL, 42, NULL, NULL) ou apenas (42) .

Isso também permite que você adicione CHECK restrição que impõe que exatamente um campo não seja NULL , para que você não obtenha vários valores de tipos diferentes.

Demonstração:
regress=> CREATE TABLE eav_ugh (
    entity_id integer,
    int_value integer,
    numeric_value numeric,
    text_value text,
    timestamp_value timestamp with time zone,
    CONSTRAINT only_one_non_null CHECK (
            (int_value IS NOT NULL AND numeric_value IS NULL AND text_value IS NULL AND timestamp_value IS NULL) OR
            (int_value IS NULL AND numeric_value IS NOT NULL AND text_value IS NULL AND timestamp_value IS NULL) OR
            (int_value IS NULL AND numeric_value IS NULL AND text_value IS NOT NULL AND timestamp_value IS NULL) OR
            (int_value IS NULL AND numeric_value IS NULL AND text_value IS NULL AND timestamp_value IS NOT NULL)
    )
);
CREATE TABLE
regress=> insert into eav_ugh (entity_id, numeric_value) select x, x from generate_series(1,5000) x;
INSERT 0 5000
regress=> select pg_relation_size('eav_ugh');                                           
 pg_relation_size 
------------------
           229376
(1 row)

regress=> CREATE TABLE no_null_cols(entity_id integer, numeric_value numeric);
CREATE TABLE
regress=> insert into no_null_cols (entity_id, numeric_value) select x, x from generate_series(1,5000) x;
INSERT 0 5000
regress=> select pg_relation_size('no_null_cols');
 pg_relation_size 
------------------
           229376
(1 row)

regress=> SELECT sum(pg_column_size(eav_ugh)) FROM eav_ugh;
  sum   
--------
 164997
(1 row)

regress=> SELECT sum(pg_column_size(no_null_cols)) FROM no_null_cols;
  sum   
--------
 164997
(1 row)

Nesse caso, o bitmap nulo não está adicionando nenhum espaço, provavelmente devido aos requisitos de alinhamento.