MySQL分表后查询所有表中的记录

表结构相同,分表后如何查询所有表的数据?可以使用union关键字

select * from table1 where type=1 union
select * from table1 where type=1 union
select * from table3 where type=1 union
select * from tablen where type=1

上述代码是对每个分表进行过滤后再连接。当然也可以先连接,再过滤数据:

select * from (
    select * from table1 union
    select * from table1 union
    select * from table3 union
    select * from tablen 
) t
where t.type=1
order by t.id desc

需要注意的是,对于排序和分组,只能在外部进行,不能在使用union的同时使用。

若需要在mybatis中使用,则可以借助foreach标签,具体查询如下:

select * from
   <foreach open="(" close=")" collection="list" item="item" separator="union">
        select * from ${item}
        <where>
            <if test="type!=null">
               and type = #{type}
            </if>
         </where>
    </foreach>           
t
order by t.id desc

其中list是传入的表名,type是传入的类型,两者都放在map中传递过来。

posted @ 2021-08-26 08:54  钟小嘿  阅读(3790)  评论(2编辑  收藏  举报