mysql模糊查詢like和regexp小結_Mysql

來源:互聯網
上載者:User

在mysql中實現模糊查詢的有like和regexp。

------------------------

like的用法許多人都是知道的,最為常用的情況就是select * from a where name like '%a%';

其中'%'代表的是任意個字元,它的效果像是Regex裡的'*',它有幾種用法:'a%','%a%','%a',分別表示以什麼開頭,存在什麼以及以什麼結尾。

另外也可以使用'_'字元,這表示一個任一字元。效果類似Regex裡面的'.'。

like是對這個欄位裡面的所有字串進行比較,效率並不高。

------------------------

regexp就是mysql的正則匹配操作符.

regexp的用法如:select * from a where name regexp 'a';其寫法可以參照Regex.像是'*','[a-z]','a|b','cc$','^b{2}$'。

------------------------

在hibernate中沒有提供regexp的直接使用功能,但是可以通過添加自訂函數的方式實現。

public class MySQL5DialectRegexp extends org.hibernate.dialect.MySQLInnoDBDialect{  public MySQL5DialectRegexp() {    super();    registerFunction( "regexp", new SQLFunctionTemplate(Hibernate.BOOLEAN, "?1 REGEXP ?2") );  }}


其中org.hibernate.dialect.MySQLInnoDBDialect是hibernate配置資訊hibernate.dialect的值,之後可以使用MySQL5DialectRegexp的路徑代替.

HQL語句可以寫作:

from A where regexp(a,'a|b|c')=1;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.