Moon
Moon

Reputation: 22575

Is this correct mysql constraint syntax?

I am learning mysql many to many relationship. While I was researching index, I found the below question.

How to properly index a linking table for many-to-many connection in MySQL?

Quassnoi answered a detail answer. Within his answer, I found the following syntax.

"ALTER TABLE table_table ADD CONSTRAINT pk_table1_table2 (table_1, table_2)"

I changed "table_table" to my joining table called "postcategory" and changed "table1" to "post", "table2" to "category"

I got a syntax error when I execute it..

What am I doing wrong? I think I didn't understand Quassnoi's intention perfectly.

Upvotes: 0

Views: 1217

Answers (2)

philwinkle
philwinkle

Reputation: 7056

Your response from above lists your ALTER TABLE statement as:

ALTER table postcategory add constraint pk_post_category(post,category);

You're defining a constraint here, not an index. If you're trying to add a primary key, it probably shouldn't be multicolumn (composite) and if so, you're missing the PRIMARY keyword. If you're trying to add a foreign key, you're missing the REFERENCES declaration.

So if it's a primary, as such, I would rewrite as:

ALTER TABLE `postcategory` ADD CONSTRAINT PRIMARY KEY `pk_post_category` (`post`,`category`);

If it's a foreign key:

ALTER TABLE `postcategory` ADD CONSTRAINT `fk_post_category` (`post`) REFERENCES `[tablename].[column]`;

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234817

You need to tell mysql what kind of constraint you are adding: primary key, unique, or foreign key. What's the full statement that is getting a syntax error?

Upvotes: 0

Related Questions