drgaeqdqiiyg14608 2015-05-29 15:38
浏览 33
已采纳

根据最长匹配组织搜索结果

I have a database table that contains project keywords. Each project has several keywords.

In the web application, a user can perform a search by entering multiple keywords to search for. If the user enters (for example) four keywords, I want to return the search result as a list of projects. The projects should be ordered based on the longest matches first. The first projects listed will the ones that matched on all four keywords, followed by projects that matched on three out of four keywords, etc.

What query can I write to return the results?

This is a rough idea of what I think the query would look like:

select projectID 
  from project_keyword 
 where keyword = '*keyword1*' 
    or keyword = '*keyword2*'
    or keyword = '*keyword3*'

But what I want is any projectID that matches all three keywords to be displayed first (if any), followed by the projectID that matched two out of three keywords, etc. projectID that don't have any matching keywords are not returned.

Example:

projectID  keyword 
---------  -------
 456       salsa
 456       guacamole
 456       tamale
 511       salsa
 511       tamale
 511       burrito
 511       taco
 654       margarita
 654       nachos
 789       margarita
 789       salsa  
 789       taco

For user keyword search for 'salsa','tamale','burrito', the query should return these projectID, in this order.

projectID
---------
 511          (matches all three)
 456          (matches two)
 789          (matches one)

How do I get the rows from the query returned in the specified order? (What query can I write to get that.)

  • 写回答

1条回答 默认 最新

  • duanheye7423 2015-05-29 19:09
    关注

    Something like this should work:

     SELECT k.projectID
       FROM project_keyword k
      WHERE k.keyword IN ('*keyword1*','*keyword2*','*keyword3*')
      GROUP BY k.projectID
      ORDER BY COUNT(DISTINCT k.keyword) DESC, k.projectID
    

    (This assumes that the table contains multiple rows for a projectID, one row for each keyword. If that's not how the table is organized, if it's a single row, and you are looking for matching keywords that occur somewhere in a column, we'd need a different query.)

    If you want to return the list of keywords that matched, you could use a GROUP_CONCAT aggregate in the SELECT list

     SELECT k.projectID
          , GROUP_CONCAT(DISTINCT k.keyword ORDER BY k.keyword) AS keywords_matched
       FROM ... 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算