sql - 选择按列总和排序的两个查询的交集

标签 sql sqlite

我有如下三个表:

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

现在搜索 appleblue 返回:

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/

相关文章:

java - 应用程序已停止 android 模拟器 genymotion

sql - 带约束的数据库 XML 字段

sql - 在 SQL 中,尝试为触发 from 条件的每个实例返回一条记录

php - 如何将mysql中的列值更改为行值?

sql - 如何根据一行中的值使一个标识符的所有值都相同?

ios - 从 iOS 中的 SQLite DB 得不到结果,但是使用 SQLite 本身得到它们

sql - Postgresql - 引用之前计算的列

python - 使用Python在SQLite中插入行后如何检索插入的ID?

python sqlite "BEGIN TRANSACTION"和 "COMMIT"命令

python - 将 SQLAlchemy 包装在 Python 的类中