今天碰到了一个需求,需要根据前端传过来的一个type参数来查询数据库,如果type为空则查询两张表,type为0则查询表A,type为1则查询表B。
思路:
使用union all,将两张表的查询结果集合并。临时表命名为表T。
sql实现:
select T.* from
(select a.id as Id, a.name as name, a.type from a
union all
select b.id as Id, b.name as name, b.type from b) T
where 1 = 1
<if test="type != null">
and T.Type = #{type}
</if>