11

I'm trying to add a column to one of of my database tables, but there is a syntax error and I can't seem to find the problem...

My current database table looks like this:

component   +  tag_id  +  item_id
------------|----------|-----------
com_content |    23    |    2642
com_content |    26    |    3481
com_content |    35    |    1868
com_content |    85    |    5827
com_content |    89    |    7882

I want it to look like this, where 'id' is auto increment and all columns part of the primary key

 id  +  component   +  tag_id  +  item_id
-----|--------------|----------|-----------
  1  |  com_content |    23    |    2642
  2  |  com_content |    26    |    3481
  3  |  com_content |    35    |    1868
  4  |  com_content |    85    |    5827
  5  |  com_content |    89    |    7882

This is my query:

DROP PRIMARY KEY
ALTER TABLE gitags_items
ADD COLUMN id INT NOT NULL AUTO_INCREMENT FIRST
PRIMARY KEY (id,component,tag_id,item_id)

However I'm getting this error message:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PRIMARY KEY ALTER TABLE gitags_items ADD COLUMN id INT NOT NULL AUTO_INC' at line 1

Any help/pointers would be much appreciated

4 Answers 4

20

The 'ALTER TABLE' bit must come first, and then each part must be seperated by a comma:

ALTER TABLE gitags_items
DROP PRIMARY KEY,
ADD COLUMN id INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (id,component,tag_id,item_id);

but I'm not sure if you can drop and create a primary key in the same staatement.

Sign up to request clarification or add additional context in comments.

Comments

2

This one works fine, there was the problem with the commas, theres no need to drop the primary key since your going to set one yourself

ALTER TABLE gitags_items ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY(id,component,tag_id,item_id);

Comments

0

First you have to make 'id' column primary key before setting autoincrement.

1 Comment

This was a problem back around v3 - in current versions, there's only a constraint for MyISAM tables where the autoincrement value must be the first entry in the index. "For MyISAM tables, you can specify an AUTO_INCREMENT secondary column in a multiple-column key" - from dev.mysql.com/doc/refman/5.1/en/create-table.html
0

Try to add the following code to my.cnf

sql-mode="NO_ENGINE_SUBSTITUTION,ERROR_FOR_DIVISION_BY_ZERO"

then, restart MySQL

# service mysqld restart

Comments

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.