您可以使用information_schema.table_constraints在MySQL中显示表的唯一约束。
语法如下。
SELECT DISTINCT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = ’yourTableName’ AND CONSTRAINT_TYPE = ’UNIQUE’;
为了理解上述语法,让我们创建一个具有UNIQUE约束的表-
mysql> create table UniqueConstraint -> ( -> Id int, -> FirstName varchar(30), -> LastName varchar(30), -> constraint uniqueFirstNameAndLastName UNIQUE(FirstName,LastName) -> );
实现上述语法以显示约束的名称,该约束是MySQL表中的唯一约束。查询如下-
mysql> select distinct CONSTRAINT_NAME -> from information_schema.TABLE_CONSTRAINTS -> where table_name = 'UniqueConstraint' and constraint_type = 'UNIQUE';
以下是输出-
| CONSTRAINT_NAME | +----------------------------+ | uniqueFirstNameAndLastName | +----------------------------+ 1 row in set, 2 warnings (0.01 sec)
如果要显示MySQL表的所有约束,请使用以下查询。
mysql> SELECT DISTINCT CONSTRAINT_NAME -> FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS -> WHERE CONSTRAINT_SCHEMA = 'MySQL'\G
以下是输出-
*************************** 1. row *************************** CONSTRAINT_NAME − PRIMARY *************************** 2. row *************************** CONSTRAINT_NAME − name 2 rows in set, 2 warnings (0.01 sec)