简体   繁体   English

如何检查外键约束存在于 oracle sql

[英]How to check foreign key constraint exists in oracle sql

Thank you very much first for your help.首先非常感谢您的帮助。 I'm here since I don't know how to program a constraint for the Video table, so that it checks if a category exists in the 'Categories' table before creating a new line inside the Video table.我在这里是因为我不知道如何为视频表编写约束,以便它在视频表中创建新行之前检查“类别”表中是否存在类别。

Categories Table:类别表:

CREATE TABLE Categories(
cat_id integer,
cat_name varchar2(128)
CONSTRAINT pk_cat PRIMARY KEY (cat_id, cat_name) 
);

Video Table:视频表:

CREATE TABLE Video(
video_id integer PRIMARY KEY,
title varchar2(128) NOT NULL,
description varchar2(128) NOT NULL,
categorie varchar2(32),
CONSTRAINT fk_vid_cat FOREIGN KEY (categorie) REFERENCES Categories,
--CONSTRAINT ck_cat_exists CHECK categorie EXISTS (cat_name) REFERENCES Categories
) ;

I don't know if it can be done directly from here, thank you very much for your help again...我不知道是否可以直接从这里完成,再次非常感谢您的帮助...

What you ask for is just what the foreign key contraint functionality provides.您所要求的正是外键约束功能所提供的。

I would start by changing the definition of the categories table so it uses cat_id only as primary key (while you also had cat_name in the primary key, which does not really make sense):我将从更改类别表的定义开始,以便它仅将cat_id用作主键(而您在主键中也有cat_name ,这实际上没有意义):

create table categories(
    cat_id integer,
    cat_name varchar2(128)
    constraint pk_cat primary key (cat_id) 
);

Then you can reference it in the video table:然后你可以在视频表中引用它:

create table video(
    video_id integer,
    title varchar2(128) not null,
    description varchar2(128) not null,
    cat_id integer,
    constraint pk_video primary key (video_id),
    constraint fk_vid_cat foreign key (cat_id) references categories(cat_id),
) ;

Note that I renamed the column and changed its datatype so it is consistent with the referenced column.请注意,我重命名了该列并更改了它的数据类型,以便它与引用的列一致。

You want the id not the name:你想要id而不是名字:

CREATE TABLE Videos (
    video_id integer PRIMARY KEY,
    title varchar2(128) NOT NULL,
    description varchar2(128) NOT NULL,
    cat_id integer,
    CONSTRAINT fk_vid_cat FOREIGN KEY (cat_id) REFERENCES Categories(cat_id)
) ;

If you want to ensure that each video has a category, then declare cat_id to be NOT NULL .如果要确保每个视频都有一个类别,则将cat_id声明为NOT NULL

The purpose of having a primary key is so that you are not repeating the string values all over the database.拥有主键的目的是避免在整个数据库中重复字符串值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM