MySQL 8.0.29でUNIQUEインデックスを作成する方法

環境
Ubuntu 22.04 LTS
MySQL 8.0.29-0ubuntu0.22.04.2

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
CREATE UNIQUE INDEX インデックス名 ON テーブル名 (col_name, ...)
CREATE UNIQUE INDEX インデックス名 ON テーブル名 (col_name, ...)
CREATE UNIQUE INDEX インデックス名 ON テーブル名 (col_name, ...)

インデックス名と対象となるテーブル名とカラム名
を指定してインデックスを作成します。複数のカラムが含まれる場合は、カンマ(,)で区切り続けて記述します。

UNIQUE インデックスを作成する手順
1.テーブルを作成します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mysql> create table testtbl(tid int, tname varchar(10));
Query OK, 0 rows affected (0.02 sec)
mysql> create table testtbl(tid int, tname varchar(10)); Query OK, 0 rows affected (0.02 sec)
mysql> create table testtbl(tid int, tname varchar(10));
Query OK, 0 rows affected (0.02 sec)

2.作成したテーブルの tid カラムを対象に UNIQUE インデックスを作成します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mysql> create unique index tid_index on testtbl(tid);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> create unique index tid_index on testtbl(tid); Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0
mysql> create unique index tid_index on testtbl(tid);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

3.作成されたインデックスを確認します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mysql> show index from testtbl\G
*************************** 1. row ***************************
Table: testtbl
Non_unique: 0
Key_name: tid_index
Seq_in_index: 1
Column_name: tid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
Visible: YES
Expression: NULL
1 row in set (0.01 sec)
mysql> show index from testtbl\G *************************** 1. row *************************** Table: testtbl Non_unique: 0 Key_name: tid_index Seq_in_index: 1 Column_name: tid Collation: A Cardinality: 0 Sub_part: NULL Packed: NULL Null: YES Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL 1 row in set (0.01 sec)
mysql> show index from testtbl\G
*************************** 1. row ***************************
        Table: testtbl
   Non_unique: 0
     Key_name: tid_index
 Seq_in_index: 1
  Column_name: tid
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
1 row in set (0.01 sec)

 

MySQL

Posted by arkgame