How do I show unique constraints of a table in MySQL?

前端 未结 5 639
庸人自扰
庸人自扰 2020-12-05 17:33

I created them, but I forgot which ones they are.

I just want to

  1. show them.
  2. remove all the constraints on a table.
相关标签:
5条回答
  • 2020-12-05 17:55

    This query returns primay keys, unique keys and foreign ones :

    show indexes from table_name;
    
    0 讨论(0)
  • 2020-12-05 18:02
    select distinct CONSTRAINT_NAME
    from information_schema.TABLE_CONSTRAINTS
    where table_name = 'table_name' and constraint_type = 'UNIQUE';
    
    0 讨论(0)
  • 2020-12-05 18:06

    The OP asked for a single table, which this will do.

    In addition, removing the last where clause will show all columns for a database which are protected by unique constraints:

    SELECT
      CONSTRAINT_NAME,
      TABLE_NAME,
      COLUMN_NAME
    FROM information_schema.KEY_COLUMN_USAGE
    WHERE
      CONSTRAINT_NAME LIKE 'UNIQ%'
      AND TABLE_SCHEMA = 'your_database_name'
      AND TABLE_NAME = 'your_table_name';
    

    Unfortunately mysql doesn't facilitate the removal of indexes based on a query result. You could execute the output of the following query to drop all unique columns in 2 queries:

    SELECT CONCAT(
      'ALTER TABLE ',
      TABLE_NAME,
      ' DROP INDEX ',
      CONSTRAINT_NAME,
      '; -- drops ',
      COLUMN_NAME,
      ' constraint'
    )
    FROM information_schema.KEY_COLUMN_USAGE
    WHERE
      CONSTRAINT_NAME LIKE 'UNIQ%'
      AND TABLE_SCHEMA = 'your_database_name';
    
    0 讨论(0)
  • 2020-12-05 18:19
    select distinct CONSTRAINT_NAME
    from information_schema.TABLE_CONSTRAINTS
    where CONSTRAINT_SCHEMA = 'mysql'
    
    0 讨论(0)
  • 2020-12-05 18:20

    This doesn't produce elegant output but is easy to remember:

    SHOW CREATE TABLE table_name;
    
    0 讨论(0)
提交回复
热议问题