개발 Tips

group by와 distinct인데

건방진참새 2018. 3. 17. 03:13

name 라는 index 에 중복된 position 들이 있는경우

group by name 으로 뽑아오면 a,b,c,d 를 가져오지만

그 a,b,c,d 의 갯수만 갖고오고싶다면 distinct 를 쓰면 됨

ㅇㅇ



mysql에서 겹치지 않는 값을 알아내는데는 2가지 정도 방법이 있다.

group by와 distinct인데, 우선 예제를 보자.


+------+----------+

| name | position |

+------+----------+

| a    | aa       |

| a    | bb       |

| a    | cc       |

| b    | aa       |

| b    | dd       |

| c    | ee       |

| c    | ac       |

| d    | ee       |

+------+----------+


위와같은 테이블 testbl 이 있다고 하자. 위의 테이블에 아래와 같은 쿼리를 실행한다면


mysql> select distinct name from testbl;

+------+

| name |

+------+

| a    |

| b    |

| c    |

| d    |

+------+

4 rows in set (0.00 sec)


mysql> select name from testbl group by name;

+------+

| name |

+------+

| a    |

| b    |

| c    |

| d    |

+------+

4 rows in set (0.00 sec)


와 같이 같은 결과가 나온다.


하지만 두가지는 쓰이는 위치가 다른 관계로 count() 시에는, group by는 각각의 개수를, distinct는 겹치지 않는 값들 전체의 개수를 뽑아올수 있게된다.

아래의 결과가 그것이다.


mysql> select name, count(name) from testbl group by name;

+------+-------------+

| name | count(name) |

+------+-------------+

| a    |           3 |

| b    |           2 |

| c    |           2 |

| d    |           1 |

+------+-------------+

4 rows in set (0.00 sec)


mysql> select count(distinct name) from testbl;

+----------------------+

| count(distinct name) |

+----------------------+

|                    4 |

+----------------------+

1 row in set (0.00 sec)



출처: http://jaweb.tistory.com/entry/한-행에-중복된-값을-겹치지않게-count-해오는법distinct-group-by [잡다구리 파크]