2014-03-06 251 views
0

我有很大的查詢。它看起來像這樣:如何將MySql查詢結果存儲在MyBatis變量中

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 

    ..... 
) 

...和兩個工會

所有我想要做的就是查詢與選擇ID開始從表2爲一些變量第一和使用後這兩個內查詢在聯合查詢中查詢結果。

我想是這樣的

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 Anywhere:

<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

相關問題