mysql从多列中搜索,多列名称搜索MySQL

I am currently working on a live search and I need to be able to find parts of a name in two columns (we need to separate first and last name). I personally would like to keep the command short, however the only way I have been able to get this to work is:

User Searches For

John Doe

Generated SQL Query

SELECT * FROM users WHERE

(first_name LIKE '%john%' OR last_name LIKE '%john%') AND

(last_name LIKE '%doe%' OR last_name LIKE '%doe%');

The search field is one box so I do some simple separation by space. Most cases this won't reach beyond three sets of clauses, was just wondering if there was any better way to do this.

NOTE:

I would like to be able to do partial matching. So I should be able to find John Doe if I look for "John Do"

SOLUTION

With the help of Rolando, I did however come up with a solution, posted for anyone else who finds this. Follow his instructions on how to create the index below, then run this:

SELECT * FROM users WHERE

(MATCH(first,last) AGAINST ('+john* +do*' IN BOOLEAN MODE))

解决方案

Your best bet here is create a FULLTEXT index that encompasses the two fields

Step 1) Create a stop word file with just three word

echo "a" > /var/lib/mysql/stopwords.txt

echo "an" >> /var/lib/mysql/stopwords.txt

echo "the" >> /var/lib/mysql/stopwords.txt

Step 2) Add these options to /etc/my.cnf

ft_min_word_len=2

ft_stopword_file=/var/lib/mysql/stopwords.txt

Step 3) Create FULLTEXT index on the first and last name columns

ALTER TABLE users ADD FULLTEXT first_last_name_index (first,last);

Step 4) Implement the MATCH function in your search

Something Like This:

SELECT * FROM users WHERE (MATCH(first,last) AGAINST ('John' IN BOOLEAN MODE)) AND (MATCH(first,last) AGAINST ('Doe' IN BOOLEAN MODE));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值