首页 > 解决方案 > 如何根据字符串的组合获取数据?

问题描述

我有数据表记录,

id, title
1, This is test the thunder
2, This is test
3, This is Testing
4, whatever
5, this is alkdjlsad asdjasjdlad
6, test
7, thunder

我想要一个这样的查询,它将获取除 2、3 和 6 之外的所有记录 解释:第 2 条第 3 条和第 6 条记录包含唯一的测试,第 1 条记录包含测试但带有雷声。

如果存在任何带有 'test' 和 'thunder' 的记录以接受此类记录,但如果纯粹带有 'test' 则忽略此类记录,

预期输出

id, title
1, This is test the thunder
4, whatever
5, this is alkdjlsad asdjasjdlad
7, thunder

我无法思考超出我的期望。

请帮我创建这个查询。

标签: mysql

解决方案


尝试REGEXP在这里使用:

SELECT *
FROM yourTable
WHERE
    title NOT REGEXP 'test' OR
    (title REGEXP 'test' AND title REGEXP '[[:<:]]thunder[[:>:]]');

在此处输入图像描述

演示

这里的逻辑是查找标题不包含子字符串 test或包含test但也包含的任何记录thunder。我的直觉反应是在 周围设置单词边界test,但看起来您实际上只是想test在标题中的任何位置找到子字符串。


推荐阅读