简体   繁体   中英

MYSQL match field to another field with comma separated keywords

So I have two tables one is questions it has a description field that I am trying to match with the topics table search_keyword field.

For example the question table description field has this:

q.description 
-------------
Have you ever traveled to China?

And the search_keyword field on topics table has this:

t.search_keywords
-------------
travel, traveled, traveling, traveler, travel agency, jet set

So basically I am trying to narrow down a result set for questions based on the description having any of the keywords.

Here is my query so far, I am given the topic URL which is a field that narrows down things a bit, but then have to narrow down even more with matching the description to the search_keywords.

SELECT * FROM question q 
         LEFT JOIN topic t ON t.category_id = q.category_id 
         WHERE t.url = 'travel' AND 
         FIND_IN_SET(q.description, t.search_keywords)

NOTE: I can't change the database unfortunately

Any help would be appreciated!

You should store the keywords as separate rows instead of comma separated values:

t.search_keywords
-------------
travel
traveled
traveling
traveler
travel agency
jet set

Then you can simply add % to both sides to find matches:

select *
from question q
left join topic t on t.category_id = q.category_id
where t.url = 'travel'
    and q.description like concat('%', t.search_keywords, '%');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM