MySQL - 唯一索引
MySQL 索引用于快速从数据库返回数据。用户无法看到索引的执行情况,它们只是用来加快查询速度。
然而,唯一索引除了加快数据检索查询速度外,还用于维护表中的数据完整性。在表列上定义唯一索引后,我们不能在该列中添加任何重复值。
MySQL 唯一索引
在 MySQL 中,可以使用 CREATE UNIQUE INDEX 语句在表的一个或多个列上创建唯一索引。
- 如果只在单个列上创建唯一索引,则该列中的所有行都必须是唯一的。
- 如果单个列中的多行都包含 NULL 值,则不能创建唯一索引。
- 如果在多个列上创建唯一索引,则这些列中的行组合必须是唯一的。
- 如果列组合中的多行包含 NULL 值,则不能在多个列上创建唯一索引。
语法
以下是在 MySQL 中创建唯一索引的语法−
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ..., columnN);
示例
首先,我们使用以下查询创建一个名为 CUSTOMERS 的表 −
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR(15) NOT NULL, AGE INT NOT NULL, ADDRESS VARCHAR(25), SALARY DECIMAL(10, 2), PRIMARY KEY(ID) );
在下面的查询中,我们使用 INSERT 语句向上面创建的表中插入一些值 -
INSERT INTO CUSTOMERS VALUES (1, 'Ramesh', '32', 'Ahmedabad', 2000), (2, 'Khilan', '25', 'Delhi', 1500), (3, 'Kaushik', '23', 'Kota', 2500), (4, 'Chaitali', '26', 'Mumbai', 6500), (5, 'Hardik','27', 'Bhopal', 8500), (6, 'Komal', '22', 'MP', 9000), (7, 'Muffy', '24', 'Indore', 5500);
表将按如下方式创建 -
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 |
3 | Kaushik | 23 | Kota | 2000.00 |
4 | Chaitali | 25 | Mumbai | 6500.00 |
5 | Hardik | 27 | Bhopal | 8500.00 |
6 | Komal | 22 | Hyderabad | 4500.00 |
7 | Muffy | 24 | Indore | 10000.00 |
现在,使用以下查询为 CUSTOMERS 表中名为 SALARY 的列创建唯一索引 -
CREATE UNIQUE INDEX unique_ind ON CUSTOMERS (SALARY);
插入重复值
现在,让我们尝试使用以下查询将 SALARY 列中的值更新为重复值(已存在的数据)-
UPDATE CUSTOMERS SET SALARY = 2000 WHERE ID = 2;
错误
上述查询导致错误,因为具有唯一索引的列不能包含重复值。
ERROR 1062 (23000): Duplicate entry '2000.00' for key 'customers.unique_ind'
在多个列上创建唯一索引
在 MySQL 中,我们还可以使用 CREATE UNIQUE INDEX 语句在表的多个列上创建唯一索引。为此,您只需将需要创建索引的列的名称传递给查询即可。
示例
假设之前创建了 CUSTOMERS 表,并使用以下查询在名为 NAME 和 AGE 的列上创建唯一索引 -
CREATE UNIQUE INDEX mul_unique_index ON CUSTOMERS(NAME, AGE);
验证
使用以下查询,我们可以列出在 CUSTOMERS 表上创建的所有索引 -
SHOW INDEX FROM CUSTOMERS\G
索引信息表显示为 -
*************************** 1. row *********************** Table: customers Non_unique: 0 Key_name: PRIMARY Seq_in_index: 1 Column_name: ID Collation: A Cardinality: 7 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL *************************** 2. row *********************** Table: customers Non_unique: 0 Key_name: mul_unique_index Seq_in_index: 1 Column_name: NAME Collation: A Cardinality: 7 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL *************************** 3. row *********************** Table: customers Non_unique: 0 Key_name: mul_unique_index Seq_in_index: 2 Column_name: AGE Collation: A Cardinality: 7 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL *************************** 4. row *********************** Table: customers Non_unique: 0 Key_name: unique_ind Seq_in_index: 1 Column_name: SALARY Collation: A Cardinality: 7 Sub_part: NULL Packed: NULL Null: YES Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL
使用客户端程序创建唯一索引
除了使用 MySQL 查询创建索引外,我们还可以使用客户端程序创建唯一索引。
语法
要通过 PHP 程序在 MySQL 表中创建唯一索引,我们需要使用 mysqli 的 query() 函数执行 CREATE UNIQUE INDEX 语句,如下所示 -
$sql = "CREATE UNIQUE INDEX uidx_tid ON tutorials_table (tutorial_id)"; $mysqli->query($sql);
要通过 JavaScript 程序在 MySQL 表中创建唯一索引,我们需要使用 mysql2 库的 query() 函数执行 CREATE UNIQUE INDEX 语句,如下所示 -
sql = "CREATE UNIQUE INDEX unique_ind ON CUSTOMERS (SALARY)"; con.query(sql);
要通过 Java 程序在 MySQL 表中创建唯一索引,我们需要使用 JDBC 的 executeUpdate() 函数执行 CREATE UNIQUE INDEX 语句,如下所示 -
String sql = "CREATE UNIQUE INDEX UIID ON tutorials_tbl (tutorial_id)"; st.executeUpdate(sql);
要通过 Python 程序在 MySQL 表中创建唯一索引,我们需要使用 MySQL Connector/Python 的 execute() 函数执行 CREATE UNIQUE INDEX 语句,如下所示 -
create_unique_index_query = "CREATE UNIQUE INDEX idx_unique_tutorial_id ON tutorials_tbl (tutorial_id)" cursorObj.execute(create_unique_index_query)
示例
以下是程序 -
$dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($mysqli->connect_errno) { printf("Connect failed: %s
", $mysqli->connect_error); exit(); } // printf('Connected successfully.
'); // UNIQUE INDEX $sql = "CREATE UNIQUE INDEX uidx_tid ON tutorials_table (tutorial_id)"; if ($mysqli->query($sql)) { printf("Unique Index created successfully!.
"); } if ($mysqli->errno) { printf("Index could not be created!.
", $mysqli->error); } $mysqli->close();
输出
获得的输出如下 -
Unique Index created successfully!.
var mysql = require('mysql2'); var con = mysql.createConnection({ host: "localhost", user: "root", password: "Nr5a0204@123" }); //连接到 MySQL con.connect(function (err) { if (err) throw err; console.log("Connected!"); console.log("--------------------------"); //创建数据库 sql = "create database TUTORIALS" con.query(sql); //选择数据库 sql = "USE TUTORIALS" con.query(sql); //创建表 sql = "CREATE TABLE CUSTOMERS (ID INT NOT NULL,NAME VARCHAR(15) NOT NULL,AGE INT NOT NULL,ADDRESS VARCHAR(25),SALARY DECIMAL(10, 2),PRIMARY KEY(ID));" con.query(sql); //插入记录 sql = "INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (1, 'Ramesh', '32', 'Ahmedabad', 2000),(2, 'Khilan', '25', 'Delhi', 1500),(3, 'kaushik', '23', 'Kota', 2500),(4, 'Chaitali', '26', 'Mumbai', 6500),(5, 'Hardik','27', 'Bhopal', 8500),(6, 'Komal', '22', 'MP', 9000),(7, 'Muffy', '24', 'Indore', 5500);" con.query(sql); //创建唯一索引 sql = "CREATE UNIQUE INDEX unique_ind ON CUSTOMERS (SALARY)"; con.query(sql); //显示索引列表 sql = "SHOW INDEX FROM CUSTOMERS;" con.query(sql, function(err, result){ if (err) throw err console.log("**List of indexes:**") console.log(result) }); });
输出
生成的输出如下 -
Connected! -------------------------- **List of indexes:** [ { Table: 'customers', Non_unique: 0, Key_name: 'PRIMARY', Seq_in_index: 1, Column_name: 'ID', Collation: 'A', Cardinality: 7, Sub_part: null, Packed: null, Null: '', Index_type: 'BTREE', Comment: '', Index_comment: '', Visible: 'YES', Expression: null }, { Table: 'customers', Non_unique: 0, Key_name: 'unique_ind', Seq_in_index: 1, Column_name: 'SALARY', Collation: 'A', Cardinality: 7, Sub_part: null, Packed: null, Null: 'YES', Index_type: 'BTREE', Comment: '', Index_comment: '', Visible: 'YES', Expression: null } ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class UniqueIndex { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/TUTORIALS"; String username = "root"; String password = "password"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println("Connected successfully...!"); //Create a unique index on the tutorials_tbl...!; String sql = "CREATE UNIQUE INDEX UIID ON tutorials_tbl (tutorial_id)"; statement.executeUpdate(sql); System.out.println("Unique Index created Successfully...!"); //showing the indexes...! ResultSet resultSet = statement.executeQuery("SHOW INDEXES FROM tutorials_tbl"); System.out.println("Following are the indexes in tutorials_tbl"); while (resultSet.next()){ System.out.println(resultSet.getString(1)+ " "+ resultSet.getString(2) +" "+resultSet.getString(3)+" " + resultSet.getString(4) +" " + resultSet.getString(4)); } connection.close(); } catch (Exception e) { System.out.println(e); } } }
输出
获得的输出如下所示 -
Connected successfully...! Unique Index created Successfully...! Following are the indexes in tutorials_tbl tutorials_tbl 0 PRIMARY 1 1 tutorials_tbl 0 UIID 1 1
import mysql.connector #建立连接 connection = mysql.connector.connect( host='localhost', user='root', password='password', database='tut' ) cursorObj = connection.cursor() create_unique_index_query = "CREATE UNIQUE INDEX idx_unique_tutorial_id ON tutorials_tbl (tutorial_id)" cursorObj.execute(create_unique_index_query) connection.commit() print('unique index created successfully.') cursorObj.close() connection.close()
输出
以下是上述代码的输出 -
unique index created successfully.