Search code examples
mysqlregexkeyword-search

MYSQL REGEXP query for keywords column


i need a regular expression to get users have only keyword 52 and users who have keyword 52,53 but not 54. below is the table structure

CREATE TABLE `User` (
  `id` int NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `keywords` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Sample record1:  100, Sam, Thompson, "50,51,52,53,54"
Sample record2:  100, Wan, Thompson, "50,52,53"
Sample record3:  100, Kan, Thompson, "53,52,50,54"

50 = sports
51 = cricket
52 = soccer
53 = baseball
54 = tennis

so far this is the query i have come up with. it gives records with all 3.

SELECT * FROM `User` WHERE keywords REGEXP '[[:<:]]52,53,54[[:>:]]' 

Solution

  • Try using FIND_IN_SET() rather than a complex regular expression:

    SELECT u.*
    FROM User
    WHERE text = '52' OR
        (FIND_IN_SET('52', text) > 0 AND FIND_IN_SET('53', text) > 0 AND
         FIND_IN_SET('54', text) = 0)
    

    Explanation:

    WHERE text = '52' -- users who have keyword 52 and only this keyword
    WHERE FIND_IN_SET('52', text) > 0 AND FIND_IN_SET('53', text) > 0 AND
         FIND_IN_SET('54', text) = 0
                      -- users who have keywords 52 and 53 but not 54