I’m trying to create a table that represents an instruction in a recipe:
+---------------------+
| recipeId (PK, FK) |
| stepNumber (PK) |
|---------------------|
| instruction |
+---------------------+
The idea is to have a primary key of (recipeId, stepNumber) where the recipeId comes from the recipe table and the stepNumber auto-increments.
When I tried to create this table, I got the following error:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Is what I’m trying to do correct/possible?
My suggestion is, create the generic
idcolumn with auto_increment first, to have a primary key in the table. Then create a unique key for bothrecipeIdandstepNumbertogether so you won’t have any duplicate combination of these 2 fields.To be able to add multiple steps for a single recipe you will need to make sure none of
recipeId,stepNumberorinstructionis set to auto-increment. The only column set to auto_increment remainsid.So the table schema for these 2 tables would look like (ignore the
categorycolumn)Let’s add a record in the
recipiestable firstThen let’s add a row
SELECTand 1 in theWHEREcondition both refer to the row withid=1in therecipiestableIFNULL(MAX(stepNumber),0)+1will select the highest step number for that recipe (if it doesn’t exist it will select “0”) +1Here’s a SQL fiddle if you want to see it working.
[EDIT]
I have never needed using a combo for the primary key but apparently following works on InnoDB provided you don’t already have a primary key in the table.