[英]PostgreSQL - key-value pair normalization
I'm trying to design a schema (on Postgres but any other SQL's fine) that supports the following requirements: 我正在尝试设计一种支持以下要求的架构(在Postgres上,但其他SQL都不错):
documents
) has a unique string ID ( id
field) and several other data fields. documents
的一行)都有一个唯一的字符串ID( id
字段)和其他几个数据字段。 So DDL should look like this: (simplified) 所以DDL应该看起来像这样:(简化)
create table documents
(
id char(32) not null
constraint documents_pkey
primary key,
data varchar(2000),
created_at timestamp,
updated_at timestamp
)
create table document_tags
(
id serial not null
constraint document_tags_pkey
primary key,
document_id char(32) not null
constraint document_tags_documents_id_fk
references documents
on update cascade on delete cascade,
tag_key varchar(200) not null,
tag_value varchar(2000) not null
)
Now my question is how can I build a query that does filtering/sorting using the tag key values? 现在我的问题是如何建立一个使用标签键值进行过滤/排序的查询? Eg Returns all documents (possibly with LIMIT/OFFSET) that does have "key1" = "value1" tag and "key2" = "value2" tags, sorted by the value of "key3" tag.
例如, 返回所有具有“ key1” =“ value1”标签和“ key2” =“ value2”标签的所有文档(可能带有LIMIT / OFFSET),并按“ key3”标签的值排序。
You can use group by
and having
: 您可以使用
group by
并having
:
select dt.document_id
from document_tags dt
where dt.tag_key = 'key1' and dt.tag_value = 'value1'
group by dt.document_id
order by max(case when dt.tag_key = 'key2' then dt.tag_value end);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.