【问题标题】:JOOQ: Select keys from a table not present in another tableJOOQ:从另一个表中不存在的表中选择键
【发布时间】:2018-01-23 07:46:38
【问题描述】:

如何获取 jooq 中另一个表中不存在的一个表中的所有键?或者等效于以下 SQL 命令:

SELECT ID FROM A WHERE ID NOT IN (SELECT ID FROM B)

【问题讨论】:

    标签: java sql jooq


    【解决方案1】:

    这将是对 jOOQ 的 1:1 翻译:

    DSL.using(configuration)
       .select(A.ID)
       .from(A)
       .where(A.ID.notIn(select(B.ID).from(B)))
       .fetch();
    

    以上假设是静态导入:

    import static org.jooq.impl.DSL.*;
    

    关于使用NOT IN的说明

    SQL NOT IN 谓词仅在子查询未产生任何 NULL 值时才能正常工作。 In the presence of a single NULL value, the entire predicate will not return any rows.

    通常最好使用NOT EXISTSas shown in this answer。或者在 jOOQ 中:

    DSL.using(configuration)
       .select(A.ID)
       .from(A)
       .where(notExists(selectOne().from(B).where(B.ID.eq(A.ID))))
       .fetch();
    

    【讨论】:

      【解决方案2】:

      试试这个:

      SELECT ID FROM A WHERE not exists (SELECT ID FROM B where B.ID = A.ID )
      

      【讨论】:

        【解决方案3】:
        Select id from A
           Minus
        Select id from B; -- all from A where not in B
        
        Select id from B
          Minus
        Select id from A; -- all from B where not in A
        

        【讨论】:

          【解决方案4】:

          在这种情况下最好使用左连接,它只是一个查询

          SELECT A.ID FROM A LEFT JOIN B ON A.ID=B.ID WHERE B.ID IS NULL;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-08-27
            • 1970-01-01
            • 2016-01-05
            • 1970-01-01
            • 2015-02-25
            • 1970-01-01
            • 2018-07-23
            • 1970-01-01
            相关资源
            最近更新 更多