mysql唯一約束
阿新 • • 發佈:2018-10-31
表結構
[sql] view plain copy- FIELD TYPE COLLATION NULL KEY
- ------------- ------------ -------------- ------ ------ ------- -------------- -------------------- -------
- id BIGINT(20) (NULL) NO PRI (NULL) AUTO_INCREMENT
- resource_name VARCHAR(128) gbk_chinese_ci YES (NULL) SELECT,INSERT,UPDATE
- resource_type TINYINT(4) (NULL) YES (NULL) SELECT,INSERT,UPDATE
給resource_name和resource_type新增聯合唯一約束 [sql] view plain copy
- ALTER TABLE jw_resource
- ADD UNIQUE KEY(resource_name, resource_type);
結果 show create table jw_resource; [javascript] view plain copy
- CREATE TABLE `jw_resource` (
- `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
- `resource_name` VARCHAR(128) DEFAULT NULL,
- `resource_type` TINYINT(4) DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `resource_name` (`resource_name`,`resource_type`)
- ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=gbk
刪除唯一約束
[sql] view plain copy- ALTER TABLE jw_role DROP INDEX resource_name;
增加一個唯一約束,並且給唯一約束起名字?
原表結構:
[html] view plain copy- mysql> show create table test_table;
- +------------+--------------------------------------------------------------------------------------------------------------------------------------------
- ---------------------------------+
- | Table | Create Table
- |
- +------------+--------------------------------------------------------------------------------------------------------------------------------------------
- ---------------------------------+
- | test_table | CREATE TABLE `test_table` (
- `id` int(50) NOT NULL AUTO_INCREMENT,
- `kk` varchar(30) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 |
- +------------+--------------------------------------------------------------------------------------------------------------------------------------------
- ---------------------------------+
- 1 row in set (0.00 sec)
- mysql> alter table test_table add unique key `kk_uq` ( kk);
- mysql> show create table test_table;
- +------------+--------------------------------------------------------------------------------------------------------------------------------------------
- --------------------------------------------------------------+
- | Table | Create Table
- |
- +------------+--------------------------------------------------------------------------------------------------------------------------------------------
- --------------------------------------------------------------+
- | test_table | CREATE TABLE `test_table` (
- `id` int(50) NOT NULL AUTO_INCREMENT,
- `kk` varchar(30) DEFAULT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `kk_uq` (`kk`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 |
- +------------+--------------------------------------------------------------------------------------------------------------------------------------------
- --------------------------------------------------------------+
- 1 row in set (0.00 sec)