如何将MySql查询结果存储在MyBatis中的变量中

时间:2014-03-06 03:27:27

标签: mysql sql database 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

    .....
)

......还有两个工会

我想要做的就是先将两个以table2中的select id开头的内部查询查询到某个变量中,然后在union查询中使用此查询结果。

我试过这样的事情

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行选择firstname,lastname,organization,email,null'是[自定义列]

完整[自定义列]如下所示:

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

1 个答案:

答案 0 :(得分: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子句,您也可以使用该子句来简化查询。