2012-04-19 42 views
2

考虑以下信息:如何在没有领先空间的情况下在数据领域进行搜索?

id message 
------------------------------------------------------------ 
1 $AA is the only way to go! 
2 This is my $AA. There are many like it. 
3 But this is my $AA. 
4 My$AA is my swag. 
5 For lack of imagination a message with $AA in the middle. 
6 Another message with at the end: $AA 

我想筛选与$ AA的所有消息:

  • $ AA可能是在消息的开始(这样:只有加上一个空格)
  • $ AA可能处于消息(这样:只有前一个空格)结束
  • $ AA可能是其他地方的消息中(用空格包围)
  • $ AA能公顷在它之前和/或之后的标点符号:$ AA。 $ AA,或($ AA)
  • 但不是任何其他charachters(字母和数字)

我通常会使用一个查询,如

SELECT * FROM messages WHERE message LIKE '%$AA%' 

但随后消息4也回。我怎样才能使查询不返回消息4?

+1

使用正则表达式。 http://dev.mysql.com/doc/refman/5.1/en/regexp.html – ethrbunny 2012-04-19 13:44:03

+0

@ethrbunny正则表达式是一个不错的选择,但是这也可以通过类似的方式实现。看到我的答案 – 2012-04-19 14:11:51

回答

1

它太容易只是在查询中添加一个空格喜欢这个 -

SELECT * FROM table_name WHERE messages LIKE '% $AA%' 

这将不包括第一行对于

使用本:

SELECT * FROM table_name WHERE messages LIKE '% $AA%' or messages like '$AA%'