If id1
is primary key in table t1
. And I want to create new table t2
and use id1 in t1
as foreign key in t2
. What should be my query? Is this one right?
create table t2(id2 int primary key, id1 int references t1(id1));
In the first step create a second table:
create table t2(id2 int primary key)
In next step we add constraint between t1 and t2. Constraint section is only name - you can use your own definition; foreign key is column name to connect with table; references section is indicate table and column to connect by foreign key.
ALTER TABLE t2 ADD CONSTRAINT fk_id FOREIGN KEY (id2) REFERENCES t1(id1);
please read this documentation for learning more about foreign key constraint https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
for your case is below
create table t1(id1 int primary key);
create table t2(id2 int , CONSTRAINT FK_t1 FOREIGN KEY (id2)
REFERENCES t1(id1));
https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html https://www.w3schools.com/sql/sql_foreignkey.asp
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.