查出集合不在表中的数据

858 阅读1分钟

导读


由于项目需要,现在需要查询一个List集合中的数据不在表中某个字段不存在的数据,并将其查询出来。

使用


原因

由于项目需要,现在需要查询一个List集合中的数据不在表中某个字段不存在的数据,并将其查询出来。

举例:

  • 集合List
List list = new ArrayList();
list.add("小明");
list.add("小张");
list.add("小丽");
list.add("小鸡");
list.add("小猪");
list.add("小二");
  • 用户表user
idnameage
1小明19
2小丽21
3张三31
4小李24
5王二34

解决方法

组装成一个临时表:将集合中的所有元素拼成一个临时表,然后使用not in,查找数据库表内所有不在临时表中的数据。

Mybatis结构如下:

<where>
   <if test="set != null and set.size != 0">
       select v.userName FROM
       <foreach collection="userList" item="item" separator="union" open="(" close=")">
           select #{item} as userName
       </foreach>
       v where v.userName not IN (select xx from table where xxxx='****')
   </if>
</where>
  • table:表名
  • xxxx='****':条件,这里可以是


例子:

<where>
   <if test="set != null and set.size != 0">
       select v.userName FROM
       <foreach collection="userList" item="item" separator="union" open="(" close=")">
           select #{item} as userName
       </foreach>
       v where v.userName not IN (select name from user where age>20);
   </if>
</where>

END


chaohenwww.yuque.com/heioky


搞定~