我有兩個表:
一桌
| ID | 姓名 | 組織編號 |
|---|---|---|
| id-1 | 一 | 組織-1 |
| id-2 | 二 | 組織-1 |
| id-3 | 三 | 組織-1 |
| id-4 | 四 | 組織-2 |
表二
| ID | 地位 |
|---|---|
| id-1 | 好的 |
| diff-id-1 | 好的 |
| diff-id-2 | 好的 |
如何撰寫一個查詢來檢索記錄TableOne,其中orgId=org-1并userId 沒有出現在TableTwo?
在 JS 中,我會寫一個 if 作為兩個 for 回圈。
我寫了一個宣告的開頭:
SELECT * from schema.TableOne
WHERE orgId = 'org-1'
但我不知道如何檢查TableOneid 到TableTwoid。
結果應該是:
| ID | 姓名 | 組織編號 |
|---|---|---|
| id-2 | 二 | 組織-1 |
| id-3 | 三 | 組織-1 |
uj5u.com熱心網友回復:
您可以exists與子查詢一起使用:
select t1.* from tableone t1 where t1.orgid='org-1'
and not exists (select 1 from tabletwo t2 where t2.id = t1.id)
uj5u.com熱心網友回復:
您可以使用 table2two 對用戶 ID 執行左外連接。ON 子句用于連接。然后添加一個 where 子句,在其中過濾 orgid = "org-1" ,并過濾掉 TableTwo 中存在匹配項的任何行,這是通過僅包含 TableTwo.Id 為空的行來完成的
SELECT
t1.*
FROM TableOne t1
LEFT JOIN TableTwo t2
ON t1.Id = t2.Id
WHERE t1.orgid = 'org-1'
AND t2.Id IS NULL
uj5u.com熱心網友回復:
您可以使用以下查詢
select * from #TableOne where orgId='org-1' and ID not in (select ID from #TableTwo)
在此處輸入圖片說明
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/361369.html
標籤:sql 数据库 PostgreSQL的
上一篇:非平凡依賴的推導
