Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

MySQL 쿼리에서 첫 번째 단어를 선택하시겠습니까?

<시간/>

MySQL 쿼리에서 첫 번째 단어를 선택하려면 SUBSTRING_INDEX()를 사용할 수 있습니다.

다음은 구문입니다 -

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

먼저 테이블을 생성하겠습니다 -

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

삽입 명령을 사용하여 테이블에 레코드 삽입 -

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)

select 명령을 사용하여 테이블의 레코드 표시 -

mysql> select *from DemoTable;

이것은 다음과 같은 출력을 생성합니다 -

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

다음은 MySQL 쿼리에서 첫 번째 단어를 선택하는 쿼리입니다 -

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

이것은 첫 번째 단어를 표시하는 다음 출력을 생성합니다 -

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