如何寫(xiě)一個(gè)能匹配字符串的mysql語(yǔ)句?
mysql的字符串匹配
需求表數(shù)據(jù)如下:
Java代碼
mysql> select * from test;
+----+-------+
id | name
+----+-------+
1 | abc**
+----+-------+
1 row in set (0.00 sec)
我想匹配 abcde,也就是一個(gè)*代表一個(gè)字符
分析:
在正則中*代表0個(gè)或者多個(gè),因此此處的存儲(chǔ)有問(wèn)題,應(yīng)該存儲(chǔ).或者_(dá)那么查詢(xún)sql可以通過(guò)like和REGEXP 來(lái)實(shí)現(xiàn)
結(jié)論:
1.采用like
Java代碼
mysql> select * from test where 'abcde' like replace(name,'*','_');
+----+-------+
id | name
+----+-------+
1 | abc**
+----+-------+
1 row in set (0.01 sec)
先替換成_然后在like 匹配
2.采用REGEXP
Java代碼
mysql> select * from test where 'abcde' regexp replace(name,'*','.');
+----+-------+
id | name
+----+-------+
1 | abc**
+----+-------+
1 row in set (0.02 sec)
替換成.然后在匹配