SQL 检查多个表中一列的唯一性

SQL check or uniqueness in one column in multipe tables

我有一个 'unique' 列,'GID_New' 在多个 table 中。有没有办法检查它在 SQL 的 QGIS 项目中的所有 table 中是否唯一?

是否可以在一次 SQL 搜索中完成而不将 table 合并为一个然后 运行 类似

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

然后检查计数 >1

我想知道非唯一 GID_New 也来自哪个 table。

数据在 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

如果您想知道其中 table 个重复项存在,那么一种选择是字符串连接。假设您的数据库使用 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