Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

MySQL gom nhóm hàng theo phần số ở đầu chuỗi trong cột VARCHAR

Kỹ thuật

Khi cột VARCHAR chứa tiền tố số (ví dụ '9844Bob'), cộng số 0 (0 + StudentId) để MySQL tự chuyển phần đầu sang số, phần chữ bị bỏ qua.

1. Tạo bảng

mysql> create table DemoTable (
    StudentId varchar(100)
);
Query OK, 0 rows affected (0.92 sec)

2. Chèn dữ liệu

mysql> insert into DemoTable values('9844Bob');
mysql> insert into DemoTable values('6375DavidMiller');
mysql> insert into DemoTable values('007');
mysql> insert into DemoTable values('97474BobBrown');
mysql> insert into DemoTable values('9844Bob56Taylor');

3. Xem dữ liệu

mysql> select * from DemoTable;
+-----------------+
| StudentId       |
+-----------------+
| 9844Bob         |
| 6375DavidMiller |
| 007             |
| 97474BobBrown   |
| 9844Bob56Taylor |
+-----------------+
5 rows in set (0.00 sec)

4. Truy vấn trích xuất phần số

mysql> select StudentId, 0+StudentId as GroupValue from DemoTable;

Kết quả:

+-----------------+------------+
| StudentId       | GroupValue |
+-----------------+------------+
| 9844Bob         | 9844       |
| 6375DavidMiller | 6375       |
| 007             | 7          |
| 97474BobBrown   | 97474      |
| 9844Bob56Taylor | 9844       |
+-----------------+------------+
5 rows in set, 4 warnings (0.00 sec)

Lưu ý: MySQL cảnh báo (warnings) do chuyển đổi chuỗi không hoàn toàn thành số. Cách này hữu ích để gom nhóm nhanh theo tiền tố số.