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

MySQL의 모든 레코드를 가져오려면 COUNT(*)를 사용해야 합니까?

<시간/>

컬럼에 대해 not null과 같은 모든 값을 원할 때마다 count(*)를 사용하십시오. count() 메서드를 사용하는 것보다 빠릅니다.

count(*)를 사용하는 구문은 다음과 같습니다. -

select count(*) as anyVariableName from yourTableName;

위의 개념을 이해하기 위해 먼저 테이블을 생성해 보겠습니다. 테이블을 생성하는 쿼리는 다음과 같습니다 -

mysql> create table CountingDemo
   -> (
   -> BookId int
   -> );
Query OK, 0 rows affected (0.60 sec)

삽입 명령을 사용하여 테이블에 일부 레코드를 삽입하십시오. 쿼리는 다음과 같습니다 -

mysql> insert into CountingDemo values(100);
Query OK, 1 row affected (0.13 sec)

mysql> insert into CountingDemo values();
Query OK, 1 row affected (0.17 sec)

mysql> insert into CountingDemo values(200);
Query OK, 1 row affected (0.12 sec)

mysql> insert into CountingDemo values(300);
Query OK, 1 row affected (0.16 sec)

mysql> insert into CountingDemo values();
Query OK, 1 row affected (0.12 sec)

select 문을 사용하여 테이블의 모든 레코드를 표시합니다. 쿼리는 다음과 같습니다 -

mysql> select *from CountingDemo;

출력

+--------+
| BookId |
+--------+
|    100 |
|   NULL |
|    200 |
|    300 |
|   NULL |
+--------+
5 rows in set (0.00 sec)

열에 null 값이 없다고 가정하면 count(*) 및 count()가 동일한 결과를 제공합니다.

그러나 이 예제에서는 BookId 열에 일부 null 값이 있습니다. 이 경우 count(*) 및 count() 모두 다른 결과를 제공합니다.

다음은 count(*) −

를 사용하는 쿼리입니다.
mysql> select count(*) as AllValue from CountingDemo;

출력

+----------+
| AllValue |
+----------+
|        5 |
+----------+
1 row in set (0.00 sec)

그녀는 count()를 사용하는 쿼리이며 null 값 계산을 고려하지 않기 때문에 다른 결과를 제공합니다. 쿼리는 다음과 같습니다 -

mysql> select count(BookId) as AllvalueWhichisNotnull from CountingDemo;

출력

+------------------------+
| AllvalueWhichisNotnull |
+------------------------+
|                      3 |
+------------------------+
1 row in set (0.00 sec)