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

前端 未结 5 650
庸人自扰
庸人自扰 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 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';
    

提交回复
热议问题