簡體   English   中英

如何在單個查詢中找到數組值的出現和缺失?

[英]How can I find array value occurrences and missing ones in a single query?

考慮一個數字字符串數組,例如 arr = ['202', '303', '1', ...] 和下表:

MyTable
code VARCHAR(255)

可以在單個查詢中找到:

  1. MyTable.code 中不存在的 arr 中的所有值?
  2. arr 中不存在的 MyTable.code 的所有值?

有什么方法可以實現嗎?

我正在使用 PostgreSQL。

您可以取消嵌套數組並使用join或類似的東西

對於第一個條件:

select el
from unnest(ar) el 
where not exists (select 1 from t where t.code = el);

類似的邏輯可用於第二個,但您可能需要select distinct

select t.code
from t 
where not exists (select 1 from unnest(ar) el  where t.code = el);

如果您想在單個查詢中同時使用兩者,則可以使用union allfull join

select el, t.code
from unnest(ar) el full join
     t 
     on t.code = el
where t.code is null or el is null;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM