使用Like子句进行MySQL多字段搜索

时间:2011-12-19 00:17:00

标签: mysql search full-text-search where-clause

我正在尝试使用MySQL中的Like子句搜索多个字段,我似乎无法取回任何结果。这是我正在使用的查询:

SELECT player_id, 1st_name, last_name, birth_date, nationality, pasition 
FROM `people` 
WHERE player_id  LIKE '%Keyword%' 
  OR 1st_name    LIKE '%Keyword%' 
  OR last_name   LIKE '%Keyword%' 
  OR birth_date  LIKE '%Keyword%' 
  OR nationality LIKE '%Keyword%'
  OR pasition    LIKE '%Keyword%' 
ORDER BY `people`.`1st_name` ASC LIMIT 0 , 60

关键字是php传递的变量。

1 个答案:

答案 0 :(得分:1)

您应该使用FULLTEXT索引。您可以搜索多个列,它比使用带通配符的LIKE快几百或几千倍。

CREATE FULLTEXT INDEX ft_people ON `people` 
  (player_id, `1st_name`, last_name, birth_date, nationality, position);

SELECT player_id, 1st_name, last_name, birth_date, nationality, pasition 
FROM `people` 
WHERE MATCH(player_id, `1st_name`, last_name, birth_date, nationality, position) 
  AGAINST('+Keyword' IN BOOLEAN MODE) 
ORDER BY `people`.`1st_name` ASC LIMIT 0 , 60

请参阅http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html

请注意,在5.6之前的MySQL中,FULLTEXT索引仅在MyISAM存储引擎中受支持。