开发者

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

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

I just want to

  1. sho开发者_如何学运维w them.
  2. remove all the constraints on a table.


select distinct CONSTRAINT_NAME
from information_schema.TABLE_CONSTRAINTS
where table_name = 'table_name' and constraint_type = 'UNIQUE';


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

SHOW CREATE TABLE table_name;


select distinct CONSTRAINT_NAME
from information_schema.TABLE_CONSTRAINTS
where CONSTRAINT_SCHEMA = 'mysql'


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

show indexes from table_name;


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜