2014-03-06 149 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

相关问题