INSTR(str,substr)

摘自小骨格子屋的 mysql中的instr()函数的用法

想要在字符串中查找某字符串可以使用instr()函数

instr()返回子字符串在字符串中首次出现的位置;如果没有找到,则返回0

用法:
1
2
3
str:从哪个字符串中搜索
substr:要搜索的子字符串
instr()函数不区分大小写

mysql instr()函数示例:
1
如图,在abcd字符串中查找是否含有字符串b,返回的字符串位置是2. 说明instr()函数返回的位置是从1开始的,如果找不到则返回0
查找字符串中包含“民”的记录

instr()函数与like运算符

在没有索引的情况下,instr()函数与like运算符的速度是一样的;在具有前缀搜索的LIKE运算符下,使用like运算符速度会更快一些

SUBSTRING(s,n,len)

MySQL 中获取子串函数 SUBSTRING(s,n,len) 带有 len 参数的格式,从字符串 s 返回一个长度同 len 字符相同的子字符串,起始于位置 n。

也可能对 n 使用一个负值。假若这样,则子字符串的位置起始于字符串结尾的第 n 个字符,即倒数第 n 个字符,而不是字符串的开头位置。

  • 实例1: 使用 SUBSTRING 函数获取指定位置处的子字符串,输入的 SQL 语句和执行结果如下所示。
1
2
3
4
5
6
7
8
9
10
mysql> SELECT SUBSTRING('computer',3) AS col1,
-> SUBSTRING('computer',3,4) AS col2,
-> SUBSTRING('computer',-3) AS col3,
-> SUBSTRING('computer',-5,3) AS col4;
+--------+------+------+------+
| col1 | col2 | col3 | col4 |
+--------+------+------+------+
| mputer | mput | ter | put |
+--------+------+------+------+
1 row in set (0.00 sec)
  • 实例2:
1
2
3
4
5
# 返回cat_array_content最后一个字符
SUBSTRING_INDEX(SUBSTRING_INDEX(`@cat_array_content`,',',len),',',-1)
SUBSTRING('computer'3) 返回从第 3 个位置开始到字符串结尾的子字符串,结果为“mputer”;SUBSTRING('computer'34) 返回从第 3 个位置开始长度为 4 的子字符串,结果为“mput”;

SUBSTRING(computer,-3) 返回从倒数第 3 个位置到字符串结尾的子字符串,结果为“ter”;SUBSTRING(computer,-53) 返回从倒数第 5 个位置开始长度为 3 的子字符串,结果为“put”。
统计各数据库超过300w的表
1
2
3
select table_schema,table_name,TABLE_ROWS
from information_schema.tables
where table_schema in ('xxx','xxx') and TABLE_ROWS > 3000000;