Search code examples
mysqlsqlddl

Can we use constraint name of a primary key as foreign key reference?


For example, I'm creating two tables as shown below:

create table A (
  department_id int,
  college_id int,
  constraint Pk_name primary key(department_id,college_id)
);

create table B (
  student_name varchar(75),
  department_id int,
  college_id int,
  foreign key(department_id,college_id) references A(Pk_name)
);

Can I write like this?


Solution

  • I don't think so because there's no way that the RDBMS could know whether PK_name is a column or a constraint name so I suggest if you stick with the usual :

    create table A ( department_id int, college_id int, constraint Pk_name primary key(department_id,college_id) );

    create table B ( student_name varchar(75), department_id int, college_id int, foreign key(department_id,college_id) references A(department_id,college_id) );

    I will update the answer once I find an other answer .