Sql 选择按列和排序的两个查询的交集

Sql 选择按列和排序的两个查询的交集,sql,sqlite,Sql,Sqlite,我有以下三个表格: documents (id, content) words (id, word) word_document (word_id, document_id, count) Words表包含所有文档中出现的所有单词,word_文档将单词与文档关联,以及文档中该单词的计数 我想编写一个查询来搜索两个单词,并只返回两个单词都按文档中两个单词的总数排序的文档 比如说 DocA: green apple is not blue DocB: blue apple is blue Do

我有以下三个表格:

documents (id, content) 
words (id, word) 
word_document (word_id, document_id, count)
Words表包含所有文档中出现的所有单词,word_文档将单词与文档关联,以及文档中该单词的计数

我想编写一个查询来搜索两个单词,并只返回两个单词都按文档中两个单词的总数排序的文档

比如说

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

我成功地使用了intersect,但它没有返回计数和,也没有顺序

我认为这应该可以做到:

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

对于那些想要这样做的人,这只适用于:

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

您可以从内部查询创建临时表,并在该表上执行外部查询。可以递归地完成更多的单词。

马哈茂德的回答对我来说很有效,我不知道哪一个更好。但我认为他的更好,因为它只查询了一次word_文档!