05|Oracle の学習 (UNIQUE 制約)

1. UNIQUE制約の概要

  • 別名: 一意キー制約。データ テーブル内のフィールド値の一意性を制限するために使用されます。
    ここに画像の説明を挿入

1.1 UNIQUE と主キーの違い:

  • テーブルごとに主キー/結合主キーが 1 つだけ存在します。
  • UNIQUE 制約は、テーブル内の複数のフィールドに存在できます。例: 生徒の電話番号と ID 番号は一意です。

2. 一意制約を追加する

2.1 テーブル作成時に追加する

ここに画像の説明を挿入

2.1.1 ケース
  • 学生情報テーブルを作成し、電話番号を唯一の制約として設定します。
create table tb_students(
    stu_num char(5) not null,
    stu_name varchar(10) not null,
    stu_sex char(1) not null,
    stu_age number(2) not null,
    stu_tel char(11) not null,
    constraint uq_student_tel UNIQUE(stu_tel)
);

実際の開発では、以下が一般的に使用されます。stu_tel の直後に unique を追加するだけです。

create table tb_students(
    stu_num char(5) not null,
    stu_name varchar(10) not null,
    stu_sex char(1) not null,
    stu_age number(2) not null,
    stu_tel char(11) not null unique
);

2.2 テーブルを作成したら追加する

ここに画像の説明を挿入

2.2.1 ケース
  • 一意のキーを持たない学生情報テーブルを作成します。
create table tb_students(
    stu_num char(5) not null,
    stu_name varchar(10) not null,
    stu_sex char(1) not null,
    stu_age number(2) not null,
    stu_tel char(11) not null
);
  • 次に、テーブルに一意のキー stu_tel を追加します。
alter table tb_students
add constraint uq_student_tel
unique(stu_tel);

3. 一意制約を削除します

ここに画像の説明を挿入

3.1 事例

  • 一意制約 uq_student_tel を削除します。
alter table tb_students
drop constraint uq_student_tel;

おすすめ

転載: blog.csdn.net/qq_41714549/article/details/132062568