萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> oracle教程 >> oracle UNIQUE / DISTINCT用法

oracle UNIQUE / DISTINCT用法

   oracle unique約束,在這裡拿出來和大家分享一下,希望對大家有用。如果某個約束只作用於單獨的字段,即可以在字段級定義約束,也可以在表級定義約束,但如果某個約束作用於多個字段,必須在表級定義約束

  ◆在定義約束時可以通過constraint關鍵字為約束命名,如果沒有指定,oracle將自動為約束建立默認的名稱定義primary key約束(單個字段)

  create table employees (empno number(5) primary key,...) 指定約束名

  create table employees (empno number(5) constraint emp_pk primary key,...)

  sql>

  sql> create table purchase (

  2 product_name varchar2(25),

  3 quantity number(4,2),

  4 purchase_date date,

  5 salesperson varchar2(3)

  6 );

  table created.

  sql>

  sql> insert into purchase values ('a', 1, '14-jul-03', 'ca');

  1 row created.

  sql> insert into purchase values ('b', 75, '14-jul-03', 'bb');

  1 row created.

  sql> insert into purchase values ('c', 2, '14-jul-03', 'ga');

  1 row created.

  sql> insert into purchase values ('d', 8, '15-jul-03', 'ga');

  1 row created.

  sql> insert into purchase values ('a', 20, '15-jul-03', 'lb');

  1 row created.

  sql> insert into purchase values ('b', 2, '16-jul-03', 'ca');

  1 row created.

  sql> insert into purchase values ('c', 25, '16-jul-03', 'lb');

  1 row created.

  sql> insert into purchase values ('d', 2, '17-jul-03', 'bb');

  1 row created.

  sql>

  sql> select unique product_name

  2 from purchase

  3 order by product_name;

  product_name

  -------------------------

  a

  b

  c

  d

  4 rows selected.

  sql>

  sql> select distinct product_name

  2 from purchase

  3 order by product_name;

  product_name

  -------------------------

  a

  b

  c

  d

  4 rows selected.

  sql>

  sql>

  sql> drop table purchase;

  table dropped.

  sql>

  oracle 主鍵和unique索引 有什麼區別

  主鍵約束:建立此約束後,對指定列進行唯一約束,並且自動生成一個聚集的索引。外表可以通過外鍵的形式連接該列。等等...

  unique唯一約束:只是對指定列進行唯一的約束。

copyright © 萬盛學電腦網 all rights reserved