我有如下三个表:
documents (id, content)
words (id, word)
word_document (word_id, document_id, count)
Words 表包含所有文档中出现的所有单词,word_document 将单词与文档以及该文档中该单词的计数相关联。
我想编写一个查询来搜索两个词,并只返回两个词都按文档中两个词的计数之和排序的文档。
例如
DocA: green apple is not blue
DocB: blue apple is blue
DocC: red apple is red
现在搜索 apple 和 blue 返回:
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
关于sql - 选择按列总和排序的两个查询的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13883900/