2017-11-25 66 views
0

我試圖設計一個架構(在Postgres的,但任何其他SQL的罰款),支持以下要求:PostgreSQL的 - 鍵值對標準化

  • 每個文檔(表documents行)有唯一的字符串ID(id字段)和其他幾個數據字段。
  • 每個文檔可以附加0個或更多標籤(即字符串鍵值對),目標是構建一個系統,讓用戶使用這些字符串鍵值對對文檔進行排序或過濾。例如。 「告訴我,有一個標籤的所有文檔‘鍵1’與‘值1’值,並使用的標記值排序輸出‘KEY3’

因此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 
) 

現在我的問題是如何建立一個查詢,使用標籤鍵值進行過濾/排序?例如返回所有具有「key1」=「value1」標籤和「標籤」的文檔(可能帶有LIMIT/OFFSET) key2「=」value2「標籤,按」key3「標籤的值排序

回答

1

您可以使用group byhaving

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); 
+0

我應該爲這個查詢添加哪些索引? –

+1

最佳索引是'document_tags(tag_key,tag_value,document_id)'。 –