COUNT로 SELECT를 수행하려면 집계 함수 COUNT()를 사용하십시오. 먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(100), Subject varchar(100) ); Query OK, 0 rows affected (0.54 sec)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
mysql> insert into DemoTable(Name,Subject) values('John','MySQL'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(Name,Subject) values('John','Java'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','MongoDB'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','Java'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','MySQL'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Name,Subject) values('John','MySQL'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(Name,Subject) values('Carol','MongoDB'); Query OK, 1 row affected (0.26 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select *from DemoTable;
출력
+----+-------+---------+ | Id | Name | Subject | +----+-------+---------+ | 1 | John | MySQL | | 2 | John | Java | | 3 | Carol | MongoDB | | 4 | Carol | Java | | 5 | Carol | MySQL | | 6 | John | MySQL | | 7 | Carol | MongoDB | +----+-------+---------+ 7 rows in set (0.00 sec)
다음은 MySQL에서 count를 사용하여 선택하는 쿼리입니다 -
mysql> select Name,Subject,count(Subject) from DemoTable group by Subject,Name;
출력
+-------+---------+----------------+ | Name | Subject | count(Subject) | +-------+---------+----------------+ | John | MySQL | 2 | | John | Java | 1 | | Carol | MongoDB | 2 | | Carol | Java | 1 | | Carol | MySQL | 1 | +-------+---------+----------------+ 5 rows in set (0.00 sec)