2016-11-20 74 views
2

我有一個名爲Index表具有列idvalue,其中id是一個自動遞增BIGINT和value是一個英文單詞爲varchar。SQL指數基於搜索

我有一個名爲Search的表,它與表Index有關係。對於每個搜索,您可以定義它應該在名爲Article的表中搜索哪些索引。

Article也與表Index有關係。

限定的關係的表格是:

Searches_Indexes與列id_searchid_index

Articles_Indexes帶有列id_articleid_index

我想找到所有包含相同搜索索引的文章。

例如:我有一個Search使用索引laptopdell,我想檢索所有Article S的同時包含索引,不只是一個。

到目前爲止,我有這樣的:

SELECT ai.id_article 
FROM articles_indexes AS ai 

INNER JOIN searches_indexes AS si 
ON si.id_index = ai.id_index 

WHERE si.id_search = 1 

如何讓我的SQL只全部SearchIndex ES返回Article S'

編輯:

樣本數據:

文章:

id | name   | description   | ... 
1 | 'Dell Laptop' | 'New Dell Laptop...' | ... 
2 | 'HP Laptop' | 'Unused HP Laptop...' | ... 
... 

搜索:

id | name     | id_user | ... 
1 | 'Dell Laptop Search' | 5  | ... 

指數:

id | value 
1 | 'dell' 
2 | 'laptop' 
3 | 'hp' 
4 | 'new' 
5 | 'unused' 
... 

Articles_Indexes:

Articleid 1(戴爾筆記本電腦)具有Index ES '戴爾', '膝上型', '新'。

Articleid 2(惠普筆記本電腦)有Index es'筆記本電腦','hp','未使用'。

id_article | id_index 
1   | 1 
1   | 2 
1   | 4 
... 
2   | 2 
2   | 3 
2   | 5 
... 

Searches_Indexes:

Searchid 1只包含2個Index ES, '戴爾' 和 '膝上型':

id_search | id_index 
1   | 1 
1   | 2 

需要的輸出:

id_article 
1 
+2

表稱爲搜索和索引...你有哪些表 - 列,在哪裏,選擇和值? – jarlh

+0

已更新,使其更清晰一點。我有兩個關係表'Searches_Indexes'和'Articles_Indexes',它們基本上定義哪些搜索具有哪些索引,哪些文章具有哪些索引。 –

+0

[編輯]你的問題,並根據這些數據添加一些樣本數據和預期的輸出。 [_Formatted_](http://dba.stackexchange.com/help/formatting)**文本**請[無屏幕截圖](http://meta.stackoverflow.com/questions/285551/why-may-i -not-upload-images-code-on-so-when-asking-question-285557#285557) –

回答

1

如果我理解正確,您需要聚合和HAVING子句。假設有沒有重複的條目在索引的表:

SELECT ai.id_article 
FROM articles_indexes ai INNER JOIN 
    searches_indexes si 
    ON si.id_index = ai.id_index 
WHERE si.id_search = 1 
GROUP BY ai.id_article 
HAVING COUNT(*) = (SELECT COUNT(*) FROM searches_indexes si2 WHERE si2.id_search = 1); 

此計算匹配的數量,並確保它,你正在尋找的數量相匹配。

我應該補充一點。如果您想同時查找所有搜索,我傾向於將其寫爲:

SELECT si.id_search, ai.id_article 
FROM articles_indexes ai INNER JOIN 
    (SELECT si.*, COUNT(*) OVER (PARTITION BY si.id_index) as cnt 
     FROM searches_indexes si 
    ) si 
    ON si.id_index = ai.id_index 
GROUP BY si.id_search, ai.id_article, si.cnt 
HAVING COUNT(*) = si.cnt; 
0

您可以比較數組。這裏有一些例子:

create table article_index(id_article int, id_index int); 
create table search_index(id_search int, id_index int); 

insert into article_index 
select generate_series(1,2), generate_series(1,10); 
insert into search_index 
select generate_series(1,2), generate_series(1,4); 

select 
    id_article 
from article_index 
group by id_article 
having array_agg(id_index) @> (select array_agg(id_index) from search_index where id_search = 2); 

Learn more關於postgres中的數組。