Spring/Mybatis
[MyBatis] Insert Join - table끼리 join해서 insert하기
sabeom
2024. 5. 2. 14:22
Insert into + Join 쿼리
우선 join은 select용이다.
insert문에 join을 결합하여 사용한다는 말은, join하여 select한 특수한 값을 골라 insert 한다는 말과 같다.
다음과 같은 상황일때 사용할 수 있다.
Q. TB1 에는 있고, TB2에는 없는 레코드만 TB2에 추가하기

sql
INSERT INTO TB2 (코드, 년도)
(
SELECT A.코드, A.년도 -- 추가할 필드
FROM TB1 A LEFT JOIN TB2 B
ON A.코드 = B.코드
WHERE B.코드 IS NULL -- join한 TB2테이블의 필드가 NULL이라는 말은 TB2에는 없는 값을 의미한다.
)
내가 사용한 방법
- 환경
- java 8
- mybatis
- postgreSQL
<insert id="insertPadjData" parameterType="com.bit.bizportal.common.voCommon.pay.adjm.AdjmDataVO">
/* SmartroPay.xml insertPadjData */
INSERT INTO tb_mpay_adjm
(
padj_mpay_id, padj_sadj_id, padj_reg_dttm, padj_updt_dttm,
tid, otid, app_dt, app_tm, cc_dt,
cc_tm, mid, moid, svc_cd, pin_no,
goods_nm, amt, tax_amt, tax_free_amt, discount_amt,
pay_amt, coupon_amt, cpx_amt, fn_cpx_amt, green_deposit,
instmnt_mon, no_int_cl, point_cl, card_cl, bc_card_cl,
state_cd, general_fee, general_vat, no_int_fee, no_int_vat,
pnt_fee, pnt_vat, ec_fee, ec_vat, auth_fee,
auth_vat, coupon_fee, coupon_var, cpx_fee, cpx_vat,
deposit_amt, settlmnt_dt, isu_cd, fn_cd, fn_no,
app_no, ccy_cd, trans_cl
)
(
SELECT
temp.padj_mpay_id, temp.padj_sadj_id, temp.padj_reg_dttm, temp.padj_updt_dttm,
temp.tid, temp.otid, temp.app_dt, temp.app_tm, temp.cc_dt,
temp.cc_tm, temp.mid, temp.moid, temp.svc_cd, temp.pin_no,
temp.goods_nm, temp.amt, temp.tax_amt, temp.tax_free_amt, temp.discount_amt,
temp.pay_amt, temp.coupon_amt, temp.cpx_amt, temp.fn_cpx_amt, temp.green_deposit,
temp.instmnt_mon, temp.no_int_cl, temp.point_cl, temp.card_cl, temp.bc_card_cl,
temp.state_cd, temp.general_fee, temp.general_vat, temp.no_int_fee, temp.no_int_vat,
temp.pnt_fee, temp.pnt_vat, temp.ec_fee, temp.ec_vat, temp.auth_fee,
temp.auth_vat, temp.coupon_fee, temp.coupon_var, temp.cpx_fee, temp.cpx_vat,
temp.deposit_amt, temp.settlmnt_dt, temp.isu_cd, temp.fn_cd, temp.fn_no,
temp.app_no, temp.ccy_cd, temp.trans_cl
FROM tmp_mpay_adjm temp
LEFT JOIN tb_mpay_adjm tma
ON temp.tid = tma.tid and temp.state_cd = tma.state_cd
WHERE tma.padj_id is null
)
</insert>
Reference
1. 인파 - insert into join 사용해보기
https://inpa.tistory.com/entry/MYSQL-📚-INSERT-INTO-JOIN-사용해보기