【问题标题】:How to query records one table by checking record field in another?如何通过检查另一个表中的记录字段来查询记录?
【发布时间】:2021-12-30 07:40:33
【问题描述】:

我有两张桌子:

TableOne

id name orgId
id-1 One org-1
id-2 Two org-1
id-3 Three org-1
id-4 Four org-2

TableTwo

id status
id-1 Ok
diff-id-1 Ok
diff-id-2 Ok

如何编写查询以从orgId=org-1userId TableTwo 中不存在TableOne 检索记录?

在 JS 中我会写一个 if 作为两个 for 循环。

我写了一个声明的开头:

SELECT * from schema.TableOne
WHERE orgId = 'org-1'

但我不知道如何检查TableOne id 到TableTwo id。

结果应该是:

id name orgId
id-2 Two org-1
id-3 Three org-1

【问题讨论】:

    标签: sql database postgresql


    【解决方案1】:

    您可以使用以下查询

    选择 * 来自#TableOne 其中 orgId='org-1' 和身份证不在 (从#TableTwo 中选择 ID)

    enter image description here

    【讨论】:

      【解决方案2】:

      您可以使用 table2two 对用户 ID 进行左外连接。 ON 子句用于连接。 然后添加一个 where 子句,在其中过滤 for orgid = "org-1" ,然后过滤掉 TableTwo 中存在匹配项的任何行,这仅通过包含 TableTwo.Id 为 null 的行来完成

      SELECT
          t1.*
      FROM TableOne t1
      LEFT JOIN TableTwo t2
          ON t1.Id = t2.Id
      WHERE t1.orgid = 'org-1'
      AND t2.Id IS NULL
      

      【讨论】:

        【解决方案3】:

        您可以将exists 与子查询一起使用:

        select t1.* from tableone t1 where t1.orgid='org-1' 
            and not exists (select 1 from tabletwo t2 where t2.id = t1.id)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-02-01
          • 1970-01-01
          • 2022-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-09
          相关资源
          最近更新 更多