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

Chọn từ đầu tiên trong truy vấn MySQL?

Để chọn từ đầu tiên trong truy vấn MySQL, bạn có thể sử dụng SUBSTRING_INDEX ().

Sau đây là cú pháp -

select substring_index(yourColumnName,' ',1) as anyAliasName from yourTableName;

Đầu tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFullName varchar(40)
);
Query OK, 0 rows affected (0.61 sec)

Chèn bản ghi vào bảng bằng lệnh chèn -

mysql> insert into DemoTable(StudentFullName) values('John Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentFullName) values('Carol Taylor');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentFullName) values('Bob Williams');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentFullName) values('David Miller');
Query OK, 1 row affected (0.16 sec)

Hiển thị các bản ghi từ bảng bằng lệnh select -

mysql> select *from DemoTable;

Điều này sẽ tạo ra kết quả sau -

+-----------+-----------------+
| StudentId | StudentFullName |
+-----------+-----------------+
| 1         | John Smith      |
| 2         | Carol Taylor    |
| 3         | Bob Williams    |
| 4         | David Miller    |
+-----------+-----------------+
4 rows in set (0.00 sec)

Sau đây là truy vấn để chọn từ đầu tiên trong truy vấn MySQL -

mysql> select substring_index(StudentFullName,' ',1) as FirstWord from DemoTable;

Điều này sẽ tạo ra kết quả sau hiển thị từ đầu tiên -

+-----------+
| FirstWord |
+-----------+
| John      |
| Carol     |
| Bob       |
| David     |
+-----------+
4 rows in set (0.00 sec)