Home  >  Article  >  Database  >  在MySQL中使用通配符时应该注意的问题_MySQL

在MySQL中使用通配符时应该注意的问题_MySQL

WBOY
WBOYOriginal
2016-06-01 13:00:40844browse

现象:

201555121455635.jpg (338×147)

有一个表 action_conf,数据如下:
如果想获取以exp_site_10_开头的en_name的记录,sql语句该如何写?

   so easy!

select en_name from action_conf where en_name like 'exp_site_10_%'

   很自信的在idb中执行了这条sql,就会发现结果并不是所预期的。

   你会发现,执行上面的sql会把所有以 exp_site_10开头的记录都列出来了。

   原因:

   其实,这都是sql中的通配符在作怪。在sql中,下划线_是一个通配符,能匹配任何单一字符。

   既然知道原因,修改sql就很容易了。正确的sql应该是:

select en_name from action_conf where en_name like 'exp\_site\_10\_%'

   在通配符前面增加转移字符后,mysql就会把通配符视为普通字符。

   进阶:

   通配符整理:

 %                                  替代一个或多个字符

 _                                  仅替代一个字符

 [charlist]                         字符列中的任何单一字符

 [^charlist]或[!charlist]           不在字符列中的任何单一字符

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn