mysql - SQL 查询根据最大共同结果对结果进行排序

标签 mysql sql

我在进行 SQL 查询时遇到问题。我正在制作一个小型搜索引擎,其中单词到页面的映射或索引是这样保存的。 抱歉,我无法在这里发布图像,所以我尝试像这样编写输出。

+---------+---------+-----------+--------+

| word_id | page_id | frequency | degree |

+---------+---------+-----------+--------+

|    2331 |      29 |         2 |      1 |

|    2332 |      29 |         7 |      1 |

|    2333 |      29 |         4 |      1 |

|    2334 |      29 |         1 |      1 |

|    2335 |      29 |         1 |      1 |

|    2336 |      29 |         1 |      1 |

|    2337 |      29 |         2 |      1 |

|    2338 |      29 |         7 |      1 |

|    2343 |      29 |         1 |      3 |

|    2344 |      29 |         1 |      3 |

......
......
...... and so on.

Word_id 指向其他表中存在的单词,page_id 指向其他表中存在的 URL。

现在假设我想搜索“Rapid 3D Prototyping Services”。我通过查询带来了与各个单词对应的结果的并集 ->

select * from words_detail where word_id=2353 or word_id=2364 or word_id=2709 or word_id=2710;

在上面的查询中,word_ids 对应于搜索查询中的 4 个单词,结果如下。

与各个单词相对应的 page_id 的并集...

mysql>

select * from words_detail where word_id=2353 or word_id=2364 or word_id=2709 or word_id=2710;


+---------+---------+-----------+--------+

| word_id | page_id | frequency | degree |

+---------+---------+-----------+--------+

|    2353 |      29 |         2 |      4 |

|    2353 |      33 |         2 |      2 |

|    2353 |      36 |         5 |      9 |

|    2353 |      40 |         1 |      4 |

|    2353 |      41 |         1 |      9 |

|    2353 |      45 |         4 |      9 |

|    2353 |      47 |         2 |      9 |

|    2353 |      49 |         4 |      9 |

|    2353 |      52 |         1 |      4 |

|    2353 |      53 |         1 |      9 |

|    2353 |      66 |         2 |      9 |

|    2364 |      29 |         1 |      4 |

|    2364 |      34 |         1 |      4 |

|    2364 |      36 |         9 |      2 |

|    2709 |      36 |         1 |      9 |

|    2710 |      36 |         1 |      9 |

+---------+---------+-----------+--------+

16 rows in set (0.00 sec)

但我希望结果按照最大匹配排序。较早的结果应该是所有 4 个单词都匹配的情况,下一个结果应该是 3 个单词匹配的情况,依此类推。换句话说,前面的结果应该具有 4 个 word_ids 共有的 page_id,接下来的结果应该是 3 个 word_ids 共有的 page_id,依此类推。

我检查了here但这在我的情况下不起作用,因为在我的情况下,OR 条件在一行中不匹配。

如何设计这样的查询?

最佳答案

使用您的 page_id 出现次数作为匹配计数,然后按其排序。

select * from words_detail A
inner join 
(SELECT PAGE_ID
, COUNT(PAGE_ID) matchCount
from words_detail 
where word_id=2353 or word_id=2364 or word_id=2709 or word_id=2710
group by PAGE_ID) B
on A.PAGE_ID=B.PAGE_ID
where word_id=2353 or word_id=2364 or word_id=2709 or word_id=2710
order by matchCount desc

关于mysql - SQL 查询根据最大共同结果对结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28712526/

相关文章:

mysql - Redshift 中的 REGEXP_REPLACE

sql - 如何在Oracle中调整范围/间隔查询?

java - Hibernate 多对多 XML 映射中的重复行

mysql - 跟踪列表数据库

mysql - MySQL中如何使用内连接和多个条件进行计数

asp.net - 在一个查询中插入多条记录

mysql - 有没有像 pouch-couch 一样离线支持同步的关系数据库

mysql - 使用 MySQL 选择多个变量

sql - SQLite-SQL问题101

mysql - 如何减少此查询中连接表的数量?