简体   繁体   中英

How to link two relational tables in mySQL

I have two tables

  1. Video (v_id, v_duration, v_status, upload_date) in the video table the primary key is v_id.
  2. video_tags(tag_name, video_id)

The video can have many tags, that's why I separated them into two tables. The question is when I create these two tables using mySQL database, I managed to create the first table using the below sql statement, create table video (v_id int, v_duration double, v_status varchar(50) default 'needs approval', upload_date DATE, primary key(v_id))

but the second I couldn't because of misunderstanding of the reference keys.

Is this mySQL statement true?

create table video_tags(tag_name varchar(50), video_id int, primary key(vidoe_id, tag_name))

This should work:

CREATE TABLE `video_tags` (
`tag_id` INT NOT NULL,
`tag_name` VARCHAR(50) NOT NULL,
`video_id` INT NOT NULL,
 PRIMARY KEY (`tag_id`),
 INDEX `video_id` (`video_id` ASC),
 INDEX `tag_name` (`tag_name` ASC),
 CONSTRAINT `video_id_fk`
 FOREIGN KEY (`video_id`)
 REFERENCES  `video` (`v_id`))

Use another column as primary key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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