【问题标题】:MySQL fulltext search over multiple columnsMySQL 全文搜索多列
【发布时间】:2023-01-13 09:17:03
【问题描述】:

我创建了一个包含 2 列全文索引的表:

CREATE TABLE players
(
    id int NOT NULL,
    first_name varchar(25) NOT NULL,
    last_name varchar(25) NOT NULL,
    team_id int NOT NULL,
    PRIMARY KEY (id),
    FULLTEXT INDEX full_text_pname (first_name, last_name),
    CONSTRAINT p_team_id FOREIGN KEY (team_id) REFERENCES teams (id)
);

现在我想做一个 SQL 查询来接收 first_name 和 last_name 并选择具有这些值的玩家。

代替:

   SELECT first_name, last_name, team_id
   FROM players
   WHERE first_name = % s AND last_name = % s

我如何使用 match 和 against?

【问题讨论】:

  • FTS 不考虑找到单词的列,对于值中的单词排序也是如此,直到仅在一列中搜索的短语搜索。
  • 那么我该如何搜索呢?
  • 如果您需要严格的等式,那么您的变体是安全的。只需通过这两列创建复合索引。 .. , INDEX full_name (first_name, last_name), ..
  • 我也不确定使用全文索引或名称有什么意义!大多数名称中没有那么多单词,因此全文索引会派上用场。
  • 我正在使用全文索引,因为我需要(在我的作业中)。如果我在“a”列上有一个全文索引并且我正在查询:“WHERE a='bla'”,我使用的是全文索引吗? or 是匹配使用全文索引的唯一方法

标签: mysql indexing full-text-search match-against


【解决方案1】:

MATCH() 函数的语法如下:

MATCH (col1,col2,...) AGAINST (expr [search_modifier])

see documentation

所以查询将是这样的:

SELECT first_name, last_name, team_id
FROM players
WHERE MATCH ( first_name ) AGAINST ("my_first_name" IN BOOLEAN MODE) AND
      MATCH ( last_name ) AGAINST ("my_last_name" IN BOOLEAN MODE);

【讨论】:

  • 不可以。MATCH 不能很好地与 AND 一起使用。
【解决方案2】:

最快的这个

WHERE first_name = '...'
  AND last_name = '...'

INDEX(last_name, first_name)

会比使用FULLTEXT更快

中速要在两列上进行相等匹配,您需要

WHERE MATCH(last, first)  -- the order must match the index
  AGAINST('+James +Rick IN BOOLEAN MODE)

FULLEXT(last, first)

最慢这确实不是快跑:

WHERE MATCH ...
  AND MATCH ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2012-05-09
    • 2013-03-12
    相关资源
    最近更新 更多