我需要一个正则表达式来让用户只拥有关键字52和拥有关键字52,53但不是54的用户。下面是表结构
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
到目前为止,这是我提出的查询。它给出了所有3个记录。
SELECT * FROM `User` WHERE keywords REGEXP '[[:<:]]52,53,54[[:>:]]'
答案 0 :(得分:3)
尝试使用FIND_IN_SET()
而不是复杂的正则表达式:
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)
<强>解释强>
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
答案 1 :(得分:1)
SELECT * FROM `User` WHERE keywords RLIKE "^52$"; --only 52
SELECT * FROM `User` WHERE keywords RLIKE "(.*(52|53)){2}" AND keywords not RLIKE "54"; -- users who have keywords 52 and 53 but not 54
编辑:对于记录:第二个查询应该是not rlike [[:<:]]54[[:>:]]
,就像在OP的原始想法中一样,以防止匹配,例如,154。