如何比较EAV模型的字符串作为INT

问题描述 投票:-1回答:1

我已经实现了EAV数据库的模式作为一个Postgres的POC的一部分。这是下面的图尔:

entity:
id, primary key 
firstName, varchar
lastName, varchar
tenantId, int, b-tree indexed

attribute:
id, primary key
label, varchar
type, varchar, (enumerated as string from java enum , NUMERIC, TEXT, DATE)

attribute_value:
id, primary key 
attribute_id, fk reference attribute primary key
entity_id, fk reference entity primary key
value, varchar

现在我面临的问题是在比较值,则加入表所示。例如,

how do I check whether an attribute with label = 'marks12' has value <
100

value::int比较不能解决问题,因为还有其他属性,如gender不能投进去int值。如何在上述EAV设计模型进行这样的价值为中心的条件。

PS:我开到其他数据库的设计,它允许映射RDBMS /存储动态属性。

sql postgresql hibernate spring-data-jpa entity-attribute-value
1个回答
0
投票

你需要一个dynamic command.的功能应该做的工作:

create or replace function eval_condition(attr text, a_type text, op text, val text)
returns boolean language plpgsql immutable as $$
declare
    result boolean;
begin
    execute format(
        'select %L::%s %s %L::%s',
        attr, a_type, op, val, a_type)
    into result;
    return result;
end $$;

例子:

with example(attr, a_type, op, val) as (
values
    ('100',        'int',     '>',    '50'),
    ('2019-01-01', 'date',    '>',    '2019-01-02'),
    ('some text',  'text',    'like', 'some%'),
    ('99.99',      'numeric', '<',    '99.99')
)
select
    attr, a_type, op, val,
    eval_condition(attr, a_type, op, val)
from example;

    attr    | a_type  |  op  |    val     | eval_condition 
------------+---------+------+------------+----------------
 100        | int     | >    | 50         | t
 2019-01-01 | date    | >    | 2019-01-02 | f
 some text  | text    | like | some%      | t
 99.99      | numeric | <    | 99.99      | f
(4 rows)    
© www.soinside.com 2019 - 2024. All rights reserved.