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 姓名 年齡 地址 薪水
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"
});

  //Connecting to MySQL
  con.connect(function (err) {
  if (err) throw err;
  console.log("Connected!");
  console.log("--------------------------");

  //Creating a Database
  sql = "create database TUTORIALS"
  con.query(sql);

  //Select database
  sql = "USE TUTORIALS"
  con.query(sql);

  //Creating table
  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);

  //Inserting records
  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);

  //Creating Unique Indexes
  sql = "CREATE UNIQUE INDEX unique_ind ON CUSTOMERS (SALARY)";
  con.query(sql);

  //Displaying list of indexes
  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://: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
#establishing the connection
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.
廣告