SQL语句:传入一个集合A,返回A中不在数据库表中的数据

写代码碰到一个不知道用SQL语句怎么表示的逻辑

问题

问题如下,现有一个集合A,我想查数据库,查出A中有哪些元素,不在数据库的表里,并且把这些元素返回给我(自然,返回结果是A的子集)。

解决方法

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

写MyBatis的代码,形如:

<choose>
    <when test="set != null and set.size != 0">
        select v.val FROM
        <foreach collection="set" item="s" separator="union" open="(" close=")">
            select #{s} as val
        </foreach>
        v where v.val not IN (select xx from XX_table where xxxx='xxxxxx')<!-- select 自定 -->
    </when>
    <otherwise>
        select val from module where 1!=1
    </otherwise>
</choose>

关联讨论:

  1. https://stackoverflow.com/questions/14114980/getting-values-which-dont-exist-in-mysql-table
  2. https://stackoverflow.com/questions/14379096/sql-query-return-whats-not-in-table

猜你喜欢

转载自blog.csdn.net/lqadam/article/details/80529389