Computer >> Máy Tính >  >> Lập trình >> MySQL

Nhận các chữ số từ một bản ghi trong MySQL?

Sử dụng hàm CONVERT () hoặc Biểu thức chính quy. Phương thức CONVERT () chuyển đổi một giá trị từ kiểu dữ liệu này sang kiểu dữ liệu khác. Điều này sẽ tìm nạp các chữ số cho chúng tôi một cách sinh thái. Hãy để chúng tôi xem một ví dụ.

Đầu tiên, chúng ta sẽ tạo một bảng.

mysql> create table textIntoNumberDemo
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.47 sec)

Chèn một số bản ghi.

mysql> insert into textIntoNumberDemo values('John-11');
Query OK, 1 row affected (0.11 sec)

mysql> insert into textIntoNumberDemo values('John-12');
Query OK, 1 row affected (0.17 sec)

mysql> insert into textIntoNumberDemo values('John-2');
Query OK, 1 row affected (0.11 sec)

mysql> insert into textIntoNumberDemo values('John-4');
Query OK, 1 row affected (0.14 sec)

Để hiển thị tất cả các bản ghi.

mysql> select *from textIntoNumberDemo;

Đây là kết quả đầu ra.

+---------+
| Name    |
+---------+
| John-11 |
| John-12 |
| John-2  |
| John-4  |
+---------+
4 rows in set (0.00 sec)

Cú pháp để tìm nạp chữ số.

SELECT yourColumnName,CONVERT(SUBSTRING_INDEX(yourColumnName,'-',-1),UNSIGNED INTEGER) AS  yourVariableName
FROM yourTableName
order by yourVariableName;

Sau đây là truy vấn.

mysql> SELECT Name,CONVERT(SUBSTRING_INDEX(Name,'-',-1),UNSIGNED INTEGER) AS MyNumber
   -> FROM textIntoNumberDemo
   -> order by MyNumber;

Đây là kết quả đầu ra.

+---------+----------+
| Name    | MyNumber |
+---------+----------+
| John-2  |        2 |
| John-4  |        4 |
| John-11 |       11 |
| John-12 |       12 |
+---------+----------+
4 rows in set (0.00 sec)