2014-03-06 2 views
0

나는 꽤 큰 쿼리를 가지고있다. 그것은 다음과 같습니다MyBatis에 MySql 쿼리 결과를 변수로 저장하는 방법

select * from 
(
    select [custom columns] 
    from table 
    where id in 
    (
     select id 
     from table2 
     where pr_id in 
     ( 
     select id 
     from table3 
     where id = #{id} 
    ) and ac_id != #{acId} 
    ) and [some_column1] like #{pattern} 

    union 

    select [custom columns2] 
    from table 
    where id in 
    (
     select id 
     from table2 
     where pr_id in 
     ( 
     select id 
     from table3 
     where id = #{id} 
    ) and ac_id != #{acId} 
    ) and [some_column2] like #{pattern} 

    union 

    ..... 
) 

... 그리고 두 개 더 노동 조합

내가하고 싶은 모든 일부 변수 첫번째로 표 2에서 선택 ID로 시작하고 그 사용 후이 두 개의 내부 쿼리를 조회하는 것입니다

을 조합 쿼리에서 쿼리 결과.

나는이

SET @var1 = (
    select id 
     from table2 
     where pr_id in 
     ( 
     select id 
     from table3 
     where id = #{id} 
    ) and ac_id != #{acId} 
) 

select * from 
(
    select [custom columns] 
    from table 
    where id in 
    (select @var1) 
    and [some_column1] like #{pattern} 

    union 

    .... 
) 

처럼 뭔가를 시도했지만 MyBatis로 오류로 날을 제공했다. 필요한 것을 할 수있는 방법이 있습니까?

오류는 다음입니다 :

을 :

Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select * from 
    (
     select firstname, lastname, organization, email, null ' at line 11 

선택 이름, 성, 조직, 이메일, 라인 (11)의 '널은 [사용자 정의 컬럼]

전체 [사용자 지정 열이 같이있다 대신 변수를 다루는 더 잘 작동 할 수 있습니다 무엇

select firstname, lastname, organization, email, null 'applicationId', null 'applicationName', (locate(_ascii #{value}, convert(email using ascii)) - 1) 'index', length(#{value}) 'length', 'EMAIL' as 'type' 
+0

오류가 무엇입니까? –

+0

@GordonLinoff 질문을 업데이트했습니다. – Dmitriy

답변

0

은 조회에서 SQL 조각을 포함하는 것입니다. 당신의 매핑 파일에서 :

<sql id="var1"> 
    select id from table2 
    where pr_id in (...) and ac_id != #{ac_id} 
</sql> 

이제 어디서나 SQL이 단편을 포함 할 수 있습니다

<select id="big_select"> 
    select * from (
     select [cols] from table where id in (
     <include refid="var1"/> 
     ) and [col] like #{pattern} 
    union 
    ...etc... 

것은 또한 당신은 또한 단순화하는 데 사용할 수있는 SQL WITH 절,보고 할 수 있습니다 당신의 질문.

+0

답장을 보내 주셔서 감사합니다. 그런 솔루션에 대해 생각했지만 시각적으로 쿼리 크기가 줄어들 것이라고 가정합니다. 모든 것이 올바르게 처리되면 부분을 네 번 쿼리합니다. 한 번 쿼리하고 결과를 사용하고 싶었습니다. – Dmitriy

관련 문제