【发布时间】:2020-03-13 05:47:09
【问题描述】:
我在 SQL 中有 100 多个表,这些表在列上没有主键或索引。
我正在手动检查每个表的每一列,以查看它们是否具有唯一键。
如果表中不存在唯一键列,我该如何查询?
【问题讨论】:
-
当您发现特定表中的特定列名不需要检查每个表时,请尝试以下查询
我在 SQL 中有 100 多个表,这些表在列上没有主键或索引。
我正在手动检查每个表的每一列,以查看它们是否具有唯一键。
如果表中不存在唯一键列,我该如何查询?
【问题讨论】:
这里你需要找到属于特定表的列名:
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%write here column name%';
【讨论】:
请尝试以下查询
select stat.table_schema as database_name,
stat.table_name,
stat.index_name,
group_concat(stat.column_name
order by stat.seq_in_index separator ', ') as columns,
tco.constraint_type
from information_schema.statistics stat
join information_schema.table_constraints tco
on stat.table_schema = tco.table_schema
and stat.table_name = tco.table_name
and stat.index_name = tco.constraint_name
where stat.non_unique = 0
and stat.table_schema not in ('information_schema', 'sys',
'performance_schema', 'mysql')
and (tco.constraint_type !='UNIQUE' OR tco.constraint_type !='PRIMARY KEY') //You can made changes here if needed
group by stat.table_schema,
stat.table_name,
stat.index_name,
tco.constraint_type
order by stat.table_schema,
stat.table_name;
【讨论】:
你可能想尝试这样的事情
SELECT schema_name(t.schema_id), t.name, i.name
FROM sys.indexes i
INNER JOIN sys.tables t ON t.object_id= i.object_id
WHERE i.type>0 and t.is_ms_shipped=0 and t.name<>'sysdiagrams'
and (is_unique_constraint=1)
礼貌:This link
【讨论】: