2012-12-14 31 views
2

我有三個表如下:兩個查詢的選擇路口由列的總和排序

documents (id, content) 
words (id, word) 
word_document (word_id, document_id, count) 

字表擁有所有的話發生在所有文件和word_document涉及一個字的文件和計數該文件中的那個詞。

我想編寫一個查詢來搜索兩個單詞,並只返回兩個單詞按文檔中兩個單詞的計數總和排序的文檔。

例如

DocA: green apple is not blue 
DocB: blue apple is blue 
DocC: red apple is red 

現在蘋果藍色返回一個搜索:

DocA, 3 
DocB, 2 

因爲...:

DocA contains both words and 3 of them 
DocB contains both words and 2 of them 
DocC only contains one word 

我用相交成功,但它不返回計數總和和沒有順序。

回答

0

對於那些誰想要這個,這僅適用:

select wd.document_id, (wd.count + d.count) as tcount from word_document as wd 
join words as w on w.id = wd.word_id 
join 
(select document_id, count from word_document 
join words on words.id = word_document.word_id 
where words.word = "apple") d on d.document_id=wd.document_id 
where w.word = "blue" order by tcount desc 

您可以從內部查詢創建臨時表並執行對外部。它可以遞歸地完成更多的單詞。

0

這應該這樣做,我認爲:

select a.document_id, a.count + b.count 
from 
(
select document_id, count 
from word_document 
where word_id = 'apple' 
group by document_id 
) a 
INNER JOIN 
(
select document_id, count 
from word_document 
where word_id = 'blue' 
group by document_id 
) b 
ON a.document_id = b.document_id 
ORDER BY a.count + b.count 
+0

馬哈茂德答案爲我工作,我不知道哪一個更好的表現。但是我認爲他一次更好地查詢word_document! – Ali

+0

@Ali,那麼你應該接受答案。 –