Question

Ok, I have a table that will look something like this:

Post
 ˪ Id
 ˪ Version
 ˪ Title
 ˪ Content

The idea is that the Id and Version together will be the primary key since you can have a single post multiple times but of different versions.

My question is this: I would like to have the Id to auto increment. Is this possible in a setup like this? Will things be messed up when I insert the second version of a post for example?


Seems like I need to clear some things up here. What I would like is to do something like this:

INSERT INTO posts VALUES (NULL, 0, "A title", "Some content");

That would create a new post with some auto incremented id. Let's say it got the id 7. I now want to create a new version:

INSERT INTO posts VALUES (7, 1, "A new title", "Some adjusted content");

Would that work? or would the id still get an auto incremented value? And even if it did work, am I doing something I shouldn't from a database design point of view, et cetera?

Was it helpful?

Solution

Consider the following example data:

id  version  title  content   
1     1        t1     c1
2     1        t2     c2

Now a user changes title and content of a post, creating a new row with auto-incremented id:

3     2        t3     t3

This is version two of some post, but you cannot see if it is a new version of post one (entry with id 1) or post two (entry with id 2).

You need something to identify the post. You can add a post_id column to your table as Tobias suggests in his answer.

Further, it is possible to remove the auto-incremented id completely and use a composite primary key (post_id,version) - the main point is to have a post_id which is not incremented automatically so that you can have data like that:

post_id  version  title  content   
1           1        t1     c1
2           1        t2     c2 
1           2        t3     t3

Here, it is clear that the third row represents a new version of post 1.

OTHER TIPS

I would do it like this:

Post:  
- ID (your primary key with auto_increment)
- post_id (this is which post you mean)
- version
- title
- content

The new ID only specifies a unique ID for this dataset. The post_id then specifies to which post this dataset belongs an the version stands for the revision of the entry.

Why don't you use the Id as some kind of version indicator, otherwise you'd have two columns serving the same purpose which is considered a flaw in DB design.

You would use a composite primary key where id and version together identify the entry. You can then auto_increment id. When you add a new entry it will auto increment. When you revise a post you explicitly define id and revision and id will not be incremented.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top