MySQL에서 필드를 연결하려면 GROUP BY와 함께 GROUP_CONCAT()을 사용할 수 있습니다. 먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(30), StudentScore int ); Query OK, 0 rows affected (0.51 sec)
삽입 명령을 사용하여 테이블에 레코드 삽입 -
mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',90); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',70); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',50); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('David',60); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',99); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable( StudentName,StudentScore) values('David',88); Query OK, 1 row affected (0.18 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select * from DemoTable;
이것은 다음과 같은 출력을 생성합니다 -
+-----------+-------------+--------------+ | StudentId | StudentName | StudentScore | +-----------+-------------+--------------+ | 1 | Bob | 80 | | 2 | Bob | 80 | | 3 | Chris | 90 | | 4 | Chris | 70 | | 5 | Bob | 50 | | 6 | David | 60 | | 7 | Chris | 99 | | 8 | David | 88 | +-----------+-------------+--------------+ 8 rows in set (0.00 sec)
다음은 MySQL에서 필드를 연결하는 쿼리입니다 -
mysql> select StudentName, group_concat(StudentScore separator ',') as Score from DemoTable group by StudentName;
이것은 다음과 같은 출력을 생성합니다 -
+-------------+----------+ | StudentName | Score | +-------------+----------+ | Bob | 80,80,50 | | Chris | 90,70,99 | | David | 60,88 | +-------------+----------+ 3 rows in set (0.24 sec)