연우, 장을 열다.

쿼리문은 아래와 같다. 


select 

a. product_code as product_code, 

c.head_code as head_code,

(

select rt_flag from marketprd_return_list where product_code=a.product_code and a.org_marketprd_idx='test1234'

) as rt_flag,

a.as_info as asDetail,

a.rex_info as rtngExchDetail,

'02' as dlvClf,

c.weight as prdWght,

IF(c.head_code='02' && c.center_code='A','03','01')as orgnTypCd,

a.deli_cost as dlvCst1,

a.prd_noti_type as prd_noti_type

 from

 marketprd_header_list a, 

 marketprd_return_list b,

 product_list c 

 where 

a.org_marketprd_idx = b.org_marketprd_idx 

and a.product_code=c.product_code 

and a.org_marketprd_idx='test1234' 

and b.rt_flag in('0','')  group by a.product_code order by a.order_no; 


에러가 났던 지점은 위 굵은 글씨다. 


select rt_flag from marketprd_return_list where product_code=a.product_code and a.org_marketprd_idx='test1234'


테이블 marketprd_return_list 에서는 컬럼 product_code와 org_marketprd_idx가 존재한다. 하지만 .. 위 쿼리에서는 

에러 " SQL 오류 (1242): Subquery returns more than 1 row " 가 뜬다. 


에러 문구의 뜻은 서브 쿼리에 1개 로우 이상이 조회가 된다는 뜻이다. 


왜인지 고민하다가 찾은 답은 




서브쿼리인 select rt_flag from marketprd_return_list where product_code=a.product_code and a.org_marketprd_idx='test1234' 이곳에서는 a.org_marketprd_idx가 무엇인지 모른다.. 심지어 


A='' 라고 했을때 좌항에 있는 A 컬럼은 테이블 marketprd_return_list 여야 하는데 컬럼을 다른 테이블 a 에서 요청해서 에러가 떴던 부분이다. 


결론적으로는... 




select 

 a. product_code as product_code, 

 c.head_code as head_code,

(

 select rt_flag from marketprd_return_list where product_code=a.product_code and org_marketprd_idx=a.org_marketprd_idx 

) as rt_flag,

 a.as_info as asDetail,

 a.rex_info as rtngExchDetail,

 '02' as dlvClf,

 c.weight as prdWght,

 IF(c.head_code='02' && c.center_code='A','03','01')as orgnTypCd,

 a.deli_cost as dlvCst1,

 a.prd_noti_type as prd_noti_type

 from

 marketprd_header_list a, 

 marketprd_return_list b,

 product_list c 

 where 

 a.org_marketprd_idx = b.org_marketprd_idx 

 and a.product_code=c.product_code 

 and a.org_marketprd_idx='test1234' 

 and b.rt_flag in('0','')    group by a.product_code order by a.order_no; 


위 처럼 조회하니, 원하는 결과값이 도출됐다.




여기서 얻을 결론은 조인하여 서브쿼리를 조회해올때에는 A=B 라고 지칭하면, A에 해당하는 좌항은 서브 쿼리의 테이블이어야 한다는 점이다.