Best way to do a weighted search over multiple fields in mysql?

后端 未结 6 1140
轮回少年
轮回少年 2020-12-04 14:42

Here\'s what i want to do:

  • match a search subject against multiple fields of my table
  • order the results by importance of the field and relevance of th
6条回答
  •  情深已故
    2020-12-04 15:29

    Probably this approach of doing a weighted search / results is suitable for you:

    SELECT *,
        IF(
                `name` LIKE "searchterm%",  20, 
             IF(`name` LIKE "%searchterm%", 10, 0)
          )
          + IF(`description` LIKE "%searchterm%", 5,  0)
          + IF(`url`         LIKE "%searchterm%", 1,  0)
        AS `weight`
    FROM `myTable`
    WHERE (
        `name` LIKE "%searchterm%" 
        OR `description` LIKE "%searchterm%"
        OR `url`         LIKE "%searchterm%"
    )
    ORDER BY `weight` DESC
    LIMIT 20
    

    It uses a select subquery to provide the weight for ordering the results. In this case three fields searched over, you can specify a weight per field. It's probably less expensive than unions and probably one of the faster ways in plain MySQL only.

    If you've got more data and need results faster, you can consider using something like Sphinx or Lucene.

提交回复
热议问题