如何匹配和排序相似的MySQL?

时间:2010-05-18 06:19:36

标签: mysql sql search sql-order-by similarity

目前,我正在进行搜索功能。让我们说在我的数据库中,我有这些数据:

  • 关键字1
  • 1关键字
  • KEYWORD3
  • Keysomething
  • 关键

并且用户输入:“Key”作为要搜索的关键字。这是我目前的查询:

SELECT * FROM data WHERE (
  data_string LIKE '$key%' OR 
  data_string LIKE '%$key%' OR
  data_string LIKE '%$key'
)

基本上,我有两个问题:

  1. 如何按相似性排序(排序)。从上面的例子中,我想要“Key”作为我的第一个结果。我目前的结果是:Keyword1,Keyword2,Keyword3,Keysomething和Key

  2. 我的SQL查询只搜索“data_string”列,如果我想搜索其他列,该怎么办?我需要做这样的事情:

  3. 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'
    ) -- ...
    

    有没有比Q2更好/更快的查询?

1 个答案:

答案 0 :(得分:6)

我不确定LIKE是否是正确的方法。如果您需要在文本中搜索关键字并按相关性分数对结果进行排序,则应使用MySQL Full-Text indexMySQL Full-text Search functions。对不起,如果这导致你远离你实际上想要做的事情,但我建议你看看它。来自MySQL参考手册的一些引用:

1)如何在表的多列上创建全文索引

mysql> CREATE TABLE articles (
    ->   id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
    ->   title VARCHAR(200),
    ->   body TEXT,
    ->   FULLTEXT (title,body)
    -> );

2)样本数据

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)在多个列中搜索关键字并显示结果+得分的示例查询:

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 |
+----+-------------------------------------+-----------------+