mysql 按相似度排序,如何在MySQL中按相似度进行匹配和排序?

Currently, I am doing a search function. Lets say in my database, I have this data:

Keyword1

Keyword2

Keyword3

Keysomething

Key

and the user entered: "Key" as the keyword to search. This is my current query:

SELECT * FROM data WHERE (

data_string LIKE '$key%' OR

data_string LIKE '%$key%' OR

data_string LIKE '%$key'

)

Basically, I have 2 questions:

How do I sort by (order by) similarity. From above example, I wanted "Key" as my first result. My current result is: Keyword1, Keyword2, Keyword3, Keysomething and Key

My SQL query only search by the "data_string" column, what if I want to seach others column? Do I need to do something like this:

SELECT * FROM data WHERE (

data_string LIKE '$key%' OR

data_string LIKE '%$key%' OR

data_string LIKE '%$key'

) OR (

data_other LIKE '$key%' OR

data_other LIKE '%$key%' OR

data_other LIKE '%$key'

) -- ...

Is there any better/faster query than Q2?

解决方案

I am not sure if LIKE is the right way to do this. If you need to search inside your text for keywords and sort results by relevancy score, you should use MySQL Full-Text index and MySQL Full-text Search functions. Sorry if this leads you away from what you are actually trying to do but I do recommend having one look at it. Some quotes from MySQL reference manual:

1) How to create full text index on multiple columns of a table

mysql> CREATE TABLE articles (

-> id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,

-> title VARCHAR(200),

-> body TEXT,

-> FULLTEXT (title,body)

-> );

2) Sample data

mysql> INSERT INTO articles (title,body) VALUES

-> ('MySQL Tutorial','DBMS stands for DataBase ...'),

-> ('How To Use MySQL Well','After you went through a ...'),

-> ('Optimizing MySQL','In this tutorial we will show ...'),

-> ('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),

-> ('MySQL vs. YourSQL','In the following database comparison ...'),

-> ('MySQL Security','When configured properly, MySQL ...');

3) Sample query that searches multiple columns for keywords and displays result + the score:

mysql> SELECT id, body, MATCH (title,body) AGAINST

-> ('Security implications of running MySQL as root') AS score

-> FROM articles WHERE MATCH (title,body) AGAINST

-> ('Security implications of running MySQL as root');

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

| id | body | score |

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

| 4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014 |

| 6 | When configured properly, MySQL ... | 1.3114095926285 |

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值