簡體   English   中英

SQL 檢查或在多個表中的一列中的唯一性

[英]SQL check or uniqueness in one column in multipe tables

我有一個“唯一”列,“GID_New”,它位於多個表中。 有沒有辦法檢查它是否在 SQL 的 QGIS 項目中的所有表中都是唯一的?

可以在一次 SQL 搜索中完成,而無需將表合並為一個然后運行類似

SELECT A.GID_New, count(*), A.TableName
FROM "Water_Merged" as A
Group by A.GID_New

然后檢查計數 >1

我也想知道非唯一 GID_New 來自哪個表。

數據位於 QGIS 的地理包中,因此代碼需要在 QGIS SQL 實現中工作。

您可以使用union all

select gid_new, count(*) no_matches
from (
    select gid_new from table1
    union all select gid_new from table2
    union all select gid_new from table3
) t
group by gid
having count(*) > 1

如果您想知道在哪個表中存在重復項,那么一種選擇是字符串連接。 假設您的數據庫使用string_agg() ,它看起來像:

select gid_new, count(*) no_matches, string_agg(which, ',') which_tables
from (
    select 'table1' which, gid_new from table1
    union all select 'table2', gid_new from table2
    union all select 'table3', gid_new from table3
) t
group by gid
having count(*) > 1

暫無
暫無

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

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