1

Here's my script:

create table Country
(
CountryId int primary key,
Name varchar(255)
);

create table Person
(
PersonId int primary key,
Name varchar(255),
FOREIGN KEY (CountryId) references Country(CountryId)
);

I'm transitioning from MS SQL and trying to get a grasp on MySQL and starting off with my typical hello world of Person->Country relationship to get a feel for foreign keys.

I'm getting this error on PHPMyAdmin:

SQL query:

CREATE TABLE Person(

PersonId INT PRIMARY KEY , Name VARCHAR( 255 ) , FOREIGN KEY ( CountryId ) REFERENCES Country( CountryId ) );

MySQL said:

1072 - Key column 'CountryId' doesn't exist in table

What newbie mistake am I making here?

2
  • You changed the question after I answered! The new error is due to your second table not having a 'CountryId' field. Commented Sep 10, 2012 at 19:58
  • @MattHumphrey: So I have to declare the field explicitly in another line? Commented Sep 10, 2012 at 20:01

1 Answer 1

2

That's because you had not created the column in Person that would be used in the foreign key, thus, Key column 'CountryId' doesn't exist in table. Here's how you'd do it:

CREATE TABLE Person(
    PersonId INT PRIMARY KEY , 
    Name VARCHAR( 255 ) , 
    CountryId int,
    FOREIGN KEY ( CountryId ) REFERENCES Country( CountryId )
);
Sign up to request clarification or add additional context in comments.

2 Comments

Can I write the creation and foreign key binding on the same line similar to MSSQL?
Not that I know of. But you can research here: dev.mysql.com/doc/refman/5.0/en/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.