选择以数字开头的值

Ome*_*ega 20 mysql sql select numbers

在MySQL上,我有一个表,其中包含以数字开头的数据

如何选择仅以数字开头的行?

Sar*_*raz 35

SELECT * FROM YourTable WHERE YourColumn regexp '^[0-9]+'
Run Code Online (Sandbox Code Playgroud)


cod*_*ict 8

你可以做:

SELECT *
FROM MyTable
WHERE MyColumn REGEXP '^[0-9]';
Run Code Online (Sandbox Code Playgroud)

使用的正则表达式是^[0-9].

^    - Start anchor, used to ensure the pattern matches start of the string.
[    - Start of character class.
0-9  - Any digit
]    - End of character class
Run Code Online (Sandbox Code Playgroud)

实际上,我们正在尝试在以数字开头的列中选择那些值.

演示:

mysql> select * from tab;
+-------+
| col   |
+-------+
| 1foo  |
| foo   |
| 10foo |
| foo10 |
+-------+
4 rows in set (0.00 sec)

mysql> select * from tab where col regexp '^[0-9]';
+-------+
| col   |
+-------+
| 1foo  |
| 10foo |
+-------+
2 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)


ype*_*eᵀᴹ 7

另一种方式:

WHERE LEFT(columnName,1) IN ('0','1','2','3','4','5','6','7','8','9')
Run Code Online (Sandbox Code Playgroud)

使用常见的字符集和排序规则,这将工作并使用列上的索引:

WHERE columnName >= '0' AND columnName < ':'
Run Code Online (Sandbox Code Playgroud)


小智 5

SELECT * FROM YourTable
WHERE YourColumn LIKE '[0-9]%';
Run Code Online (Sandbox Code Playgroud)

  • `SELECT*FROM \`artists \`WHERE \`artist \`LIKE'[0-9]%'`返回空. (2认同)
  • MySQL的`like`不支持这种模式.你必须使用`regexp`.例如:`SELECT*FROM foo WHERE bar REGEXP'^ [0-9]'`.https://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html (2认同)