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
)
[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
'MySQL' 카테고리의 다른 글
[mysql][문제해결] You are using safe update mode (0) | 2022.02.22 |
---|---|
MySQL null값을 유의하자 (0) | 2022.02.19 |
MySQL table과 view 차이 (0) | 2022.02.10 |
식별관계(Identifying Relationship)과 비식별관계(Non Identifying Relationship)출처: https://linuxism.ustd.ip.or.kr/512 [linuxism] (0) | 2022.01.28 |
MySQL 8.x Quick Start 04 - 테이블 관계 제약조건 걸기 (0) | 2022.01.17 |
댓글