Mysql: 如何在子查询中使用like语句过滤数据
Mysql: How to filter data by using like statement in subquery
我有两个 table 如下,我想过滤 bad_word
table
中某个单词包含的值
词不达意Table
CREATE TABLE `bad_word` (
`id` int(11) NOT NULL,
`value` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
id value
1 apple
项目table
CREATE TABLE `items` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
id name
1 buy this apple
2 buy this orrange
3 buy this mango
我想得到过滤后的最终结果
id name
2 buy this orrange
3 buy this mango
我试过的示例查询
select *
FROM items
where
items.name not like CONCAT('%', select value from bad_words , '%')
您可以使用 anti-join 方法:
SELECT i.*
FROM items i
LEFT JOIN bad_words bw
ON i.name LIKE CONCAT('%', bw.value, '%')
WHERE bw.value IS NULL;
实际上,最好在此处使用 REGEXP
,并在不良关键字周围加上字词边界:
SELECT i.*
FROM items i
LEFT JOIN bad_words bw
ON i.name REGEXP CONCAT('\b', bw.value, '\b')
WHERE bw.value IS NULL;
我有两个 table 如下,我想过滤 bad_word
table
词不达意Table
CREATE TABLE `bad_word` (
`id` int(11) NOT NULL,
`value` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
id value
1 apple
项目table
CREATE TABLE `items` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
id name
1 buy this apple
2 buy this orrange
3 buy this mango
我想得到过滤后的最终结果
id name
2 buy this orrange
3 buy this mango
我试过的示例查询
select *
FROM items
where
items.name not like CONCAT('%', select value from bad_words , '%')
您可以使用 anti-join 方法:
SELECT i.*
FROM items i
LEFT JOIN bad_words bw
ON i.name LIKE CONCAT('%', bw.value, '%')
WHERE bw.value IS NULL;
实际上,最好在此处使用 REGEXP
,并在不良关键字周围加上字词边界:
SELECT i.*
FROM items i
LEFT JOIN bad_words bw
ON i.name REGEXP CONCAT('\b', bw.value, '\b')
WHERE bw.value IS NULL;