본문 바로가기
목차
MySQL

그룹별 상위 5개 가져오기

by 지각생 2022. 2. 18.
728x90

참고 1 : UNION ALL을 배움

답변

다음을 사용하여이를 수행하는 한 가지 방법이 있습니다 UNION ALL( Demo with SQL Fiddle 참조 ). 그룹이 두 개 이상인 경우 두 그룹으로 작업 할 수 있습니다. 그룹 group수 를 지정하고 각 그룹에 대해 쿼리를 추가해야합니다 group.

(
  select *
  from mytable
  where `group` = 1
  order by age desc
  LIMIT 2
)
UNION ALL
(
  select *
  from mytable
  where `group` = 2
  order by age desc
  LIMIT 2
)

http://daplus.net/mysql-%EA%B0%81-%EA%B7%B8%EB%A3%B9%ED%99%94-%EB%90%9C-%EA%B2%B0%EA%B3%BC-%EA%B7%B8%EB%A3%B9%EC%97%90-%EB%8C%80%ED%95%9C-%EC%83%81%EC%9C%84-n-%EA%B0%9C-%EB%A0%88%EC%BD%94%EB%93%9C-%EA%B0%80%EC%A0%B8/

 

[mysql] 각 그룹화 된 결과 그룹에 대한 상위 n 개 레코드 가져 오기 - 리뷰나라

다음은 가장 간단한 예이지만 모든 솔루션을 확장 할 수 있어야하지만 많은 n 개의 상위 결과가 필요합니다. 아래 표에 개인, 그룹 및 연령 열 이있는 경우 각 그룹에서 가장 나이가 많은 두 사람

daplus.net


참고 2 : foreach의 separator="or" 기능은 알고 있었지만 활용해보기로 함.

 


List 형태를 넘겼을 경우의 예제.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<java Code>
 
List sUserTP = new ArrayList();
sUserTP.add("SP");
sUserTP.add("BX");
 
 
HashMap hm = new HashMap();
hm.put("sUser_age", 23) ;
hm.put("sUser_type", sUserTP) ;
 
 
<SQL Mapper>
 
<select id="getTList" resultType="hashmap" parameterType="hashmap">
    SELECT
        name, age
    FROM
        TB_user
    WHERE
        age = #{sUser_age} AND
        <foreach collection="sUser_type" item="type"  open="(" close=")" separator="or">
            user_type = #{type.value}
        </foreach>
</select>
 
 
또는 or 구문을 IN 구문으로 변경
 
 
<select id="getTList" resultType="hashmap" parameterType="hashmap">
    SELECT
        name, age
    FROM
        TB_user
    WHERE
        age = #{sUser_age} AND
        user_type IN
        <foreach collection="sUser_type" item="type"  open="(" close=")" separator=",">
            #{type.value}
        </foreach>
</select>



출처: https://fruitdev.tistory.com/187 [과일가게 개발자]

 


최종

그래서 만든 문장은

	<select id="getChannelWritingList" parameterType="com.MyBlog.Dto.Channel" resultType="com.MyBlog.Dto.Board">
	
			<foreach item="getChannelList" collection="getChannelList" open="" close="" separator="UNION ALL">
			
			(select * from board where channelName = #{getChannelList.title} order by date DESC limit 0,#{size})
			
			
			</foreach>
	</select>

 

각 채널별 최근 5개 게시글 그룹핑 완성

728x90

댓글