EAV Select query from spreaded value tables

泪湿孤枕 提交于 2019-12-06 09:39:21

You need an SQL join. It will look something like this:

select 
    CLIENTS.ClientID, 
    CLIENTS.ClientName, 
    ATTRIBUTES_STRING1.AttributeStringValue as Rank, 
    ATTRIBUTES_NUMERIC2.AttributeNumericValue as FileRecordsAmount
from 
    CLIENTS,
    ATTRIBUTES ATTRIBUTES1,
    ATTRIBUTES ATTRIBUTES2,
    ATTRIBUTES_STRING ATTRIBUTES_STRING1,
    ATTRIBUTES_NUMERIC ATTRIBUTES_NUMERIC2
where CLIENTS.ClientID = ATTRIBUTES_STRING1.ClientID
and CLIENTS.ClientID = ATTRIBUTES_NUMERIC2.ClientID
and ATTRIBUTES_STRING1.AttributeID = ATTRIBUTES1.AttributeID
and ATTRIBUTES_NUMERIC2.AttributeID = ATTRIBUTES2.AttributeID
and ATTRIBUTES1.AttributeName = 'Rank'
and ATTRIBUTES2.AttributeName = 'FileRecordsAmount'
;

Here is the SQL Fiddle for reference. This is my first EAV schema so I wouldn't put too much trust in it :)

Edit: Schema provided below for reference:

create table CLIENTS (
    ClientID integer primary key,
    ClientName varchar(50) not null
);

insert into CLIENTS values (1,'James');
insert into CLIENTS values (2,'Leonard');
insert into CLIENTS values (3,'Montgomery');

create table ATTRIBUTES (
    AttributeID integer primary key,
    AttributeName varchar(50) not null
);

create index ATTRIBUTE_NAME_IDX on ATTRIBUTES (AttributeName);

insert into ATTRIBUTES values (1,'Rank');
insert into ATTRIBUTES values (2,'Date');
insert into ATTRIBUTES values (3,'Salary');
insert into ATTRIBUTES values (4,'FileRecordsAmount');

create table ATTRIBUTES_STRING (
    ClientID integer,
    AttributeID integer not null,
    AttributeStringValue varchar(255) not null,
    primary key (ClientID, AttributeID)
);

insert into ATTRIBUTES_STRING values (1,1,'Captain');
insert into ATTRIBUTES_STRING values (2,1,'Chief Surgeon');
insert into ATTRIBUTES_STRING values (3,1,'Chief Engineer');

create table ATTRIBUTES_NUMERIC (
    ClientID integer,
    AttributeID integer not null,
    AttributeNumericValue numeric(10, 5) not null,
    primary key (ClientID, AttributeID)
);
insert into ATTRIBUTES_NUMERIC values (1,4,187);
insert into ATTRIBUTES_NUMERIC values (2,4,2);
insert into ATTRIBUTES_NUMERIC values (3,4,10);

Edit: Modified the select to make it easier to extend with extra attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!