Steps for MySQL to create a multi-table association

Source: Internet
Author: User

One, a pair of multi-table creation1. Create a primary table

CREATE TABLE Hosttable (
CID varchar (+) primary key,
CNAME varchar (100)
);

2. Create a table from

CREATE TABLE Fromtable (
PID varchar (+) primary key,
PName varchar (40),
Price Double,
);

3. To create a from table from a key column

ALTER TABLE fromtable add hosttable_id varchar (32);

4. Adding Constraints

ALTER TABLE fromtable add constraint fromtable _FK foreign key (hosttable_id) references hosttable (CID);

Second, many-to-many table creation

Introduces an intermediate table that stores two slave keys referenced by each of the two primary keys. Two slave keys can be repeated multiple times. In this way, many-to-many table relationships are implemented.

CREATE TABLE Intertable (

Hosttableid varchar (32),

Fromtableid varchar (32)

);

1. Add a federated primary key

ALTER TABLE intertable add primary key (Hosttableid, Fromtableid);

2. Adding constraints

ALTER TABLE intertable add constraint INTER_HOSTTABLE_FK foreign key (Hosttableid) referrences hosttable (CID);

ALTER TABLE intertable add constraint INTER_FROMTABLE_FK foreign key (Fromtableid) referrences fromtable (PID);

At this time intertable and hosttable, fromtable respectively are a pair of many

Steps for MySQL to create a multi-table association

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.