如何在Oracle中创建表时向具有特定条件的列添加约束?

时间:2017-07-28 18:17:12

标签: sql oracle

这是我用于创建表运动员的SQL:

CREATE TABLE Athlete 
(
 athelete_id NUMBER(6) PRIMARY KEY,
 athlete_lname VARCHAR2(50) NOT NULL,
 athlete_fname VARCHAR2(50) NOT NULL,
 athlete_dob DATE NOT NULL,
 athlete_email VARCHAR2(50) UNIQUE,
 athlete_gender VARCHAR2(1) NOT NULL
);

对于athlete_gender列,如何仅添加M或F的约束?

接下来是我创建Olympic_Game表的SQL:

CREATE TABLE Olympic_Game (
    og_id                NUMBER(3) NOT NULL,
    og_type_id           NUMBER(3) NOT NULL,
    og_year              NUMBER(4) NOT NULL,
    og_website           VARCHAR2(150),
    og_cancel            VARCHAR2(1) NOT NULL,
    country_country_id   NUMBER(3) NOT NULL
);

如何为og_year列和og_type_id列的组合添加UNIQUE约束?

接下来是我创建事件表的SQL:

CREATE TABLE Event (
    event_id             NUMBER(6) NOT NULL,
    sport_sport_id       NUMBER(3) NOT NULL,
    olympic_game_og_id   NUMBER(3) NOT NULL,
    event_title          VARCHAR2(100) NOT NULL,
    event_team           VARCHAR2(1) NOT NULL,
    no_per_team          NUMBER(2) NOT NULL,
    event_gender         VARCHAR2(1) NOT NULL
);

对于event_team列,如何添加Y或N的约束;默认是N?

对于no_per_team列,如何添加约束:如果event_team是N则no_per_team = 1否则no_per_team> 1;默认是1?

1 个答案:

答案 0 :(得分:0)

CREATE TABLE Athlete 
(
 athelete_id NUMBER(6) PRIMARY KEY,
 athlete_lname VARCHAR2(50) NOT NULL,
 athlete_fname VARCHAR2(50) NOT NULL,
 athlete_dob DATE NOT NULL,
 athlete_email VARCHAR2(50) UNIQUE,
 athlete_gender VARCHAR2(1) NOT NULL,
CONSTRAINT chk$athlete$gender CHECK ( athlete_gender IN ('M','F'))
);

CREATE TABLE Olympic_Game (
    og_id                NUMBER(3) NOT NULL,
    og_type_id           NUMBER(3) NOT NULL,
    og_year              NUMBER(4) NOT NULL,
    og_website           VARCHAR2(150),
    og_cancel            VARCHAR2(1) NOT NULL,
    country_country_id   NUMBER(3) NOT NULL,
    CONSTRAINT un$og$year$type UNIQUE (og_year,og_type_id )
);

CREATE TABLE Event (
    event_id             NUMBER(6) NOT NULL,
    sport_sport_id       NUMBER(3) NOT NULL,
    olympic_game_og_id   NUMBER(3) NOT NULL,
    event_title          VARCHAR2(100) NOT NULL,
    event_team           VARCHAR2(1) DEFAULT 'N' NOT NULL,
    no_per_team          NUMBER(2) DEFAULT 1 NOT NULL,
    event_gender         VARCHAR2(1) NOT NULL,
    CONSTRAINT chk$event$team CHECK ( event_team IN ('Y','N')),
    CONSTRAINT chk$event$no_team CHECK ((event_team='N' AND no_per_team=1) OR (event_team='Y' AND no_per_team>1))
);