简体   繁体   English

LIKE MySQL搜索周围的空格

[英]Spaces around a LIKE MySQL search

I have a query as follow: 我有一个查询如下:

$stmt = $conn->prepare("
SELECT news_feed.title, shows.name, shows.id, news_feed.news_id 
FROM news_feed 
JOIN shows 
ON news_feed.title 
LIKE concat('%', shows.name, '%')");

Basically it takes my table shows (with tv shows names) and look for tv shows in another table with headlines that are scraped from television news source. 基本上,它会带我的电视节目表(带有电视节目名称),然后在另一个具有从电视新闻来源抓取的标题的表中寻找电视节目。 The issue is that I recently added the show 'ER' and that anytimes I have a headline which contains ER (that's a lot of headlines), it makes a connection between the show and the headline. 问题是,我最近添加了节目“ ER”,并且只要我的标题包含ER(标题很多),它就会在节目和标题之间建立联系。 To avoid this issue, I want to capture the shows.name surrounded by two spaces. 为避免此问题,我想捕获由两个空格包围的shows.name。 I read up on stackoverflow that a good way to do so is to the brackets like so: 我阅读了stackoverflow,这样做的一个好方法是放在方括号内,如下所示:

LIKE concat('%[]', shows.name, '[]%')");

but that doesn't work. 但这不起作用。 What else can I try ? 我还能尝试什么?

Thanks! 谢谢!

I'm not familiar with the use of '[]' in a LIKE expression. 我不喜欢在LIKE表达式中使用'[]'。 I would have used concat('% ', shows.name, ' %') instead. 我本来会使用concat('% ', shows.name, ' %')

I'd go with a regular expression for this: 我会为此使用正则表达式:

WHERE shows.name RLIKE '(^|[[:blank:][:punct:]])er($|[[:blank:][:punct:]])'

This checks for (beginning of string or punctuation or blank) followed by ER followed by (end of string or punctuation or blank). 这将检查(字符串或标点符号或空格的开头),然后是ER然后是(字符串或标点符号或空格的结尾)。 I tested it with these positive values and it worked: 我用这些正值测试了它,它的工作原理是:

  • ER 急诊室
  • That ER show 那个ER秀
  • Watch ER! 看ER!

It also kept out values like Another show and err, what? 它还排除了“ Another show和“ err, what?

Addendum : here's the full query: 附录 :完整查询:

SELECT
  news_feed.title,
  shows.name,
  shows.id,
  news_feed.news_id
FROM news_feed
JOIN shows ON news_feed.title
   RLIKE CONCAT('(^|[[:blank:][:punct:]])', shows.name, '($|[[:blank:][:punct:]])')

There's a SQL Fiddle here . 有一个SQL小提琴这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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