【问题标题】:How to find unique keys in a table in SQL如何在 SQL 中查找表中的唯一键
【发布时间】:2020-03-13 05:47:09
【问题描述】:

我在 SQL 中有 100 多个表,这些表在列上没有主键或索引。

我正在手动检查每个表的每一列,以查看它们是否具有唯一键。

如果表中不存在唯一键列,我该如何查询?

【问题讨论】:

  • 当您发现特定表中的特定列名不需要检查每个表时,请尝试以下查询

标签: mysql sql database unique


【解决方案1】:

这里你需要找到属于特定表的列名:

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%'; 

【讨论】:

    【解决方案2】:

    请尝试以下查询

    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;
    

    【讨论】:

      【解决方案3】:

      你可能想尝试这样的事情

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-21
        • 1970-01-01
        • 1970-01-01
        • 2023-02-03
        • 2017-03-19
        相关资源
        最近更新 更多