Question: I am making a webapp right now and I am trying to get my head around the database design.

I have a user model(username (which is primary key), password, email, website)
I have a entry model(id, title, content, comments, commentCount)

A user can only comment on an entry once. What is the best and most efficient way to go about doing this?

At the moment, I am thinking of another table that has username (from user model) and entry id (from entry model)

```
   **username    id**
    Sonic        4
    Sonic        5
    Knuckles     2
    Sonic        6
    Amy          15
    Sonic        20
    Knuckles     5
    Amy          4

```

So then to list comments for entry 4 it searches for id=4.

**On a side note:**
Instead of storing a commentCount, would it be better to calculate the comment count from the database each time when needed?

Answer: 
Here's my recommendation for your data model:

**USERS** table

* USER\_ID (pk, int)
* USER\_NAME
* PASSWORD
* EMAIL
* WEBSITE

**ENTRY** table

* ENTRY\_ID (pk, int)
* ENTRY\_TITLE
* CONTENT

**ENTRY\_COMMENTS** table

* ENTRY\_ID (pk, fk)
* USER\_ID (pk, fk)
* COMMENT

This setup allows an ENTRY to have 0+ comments. When a comment is added, the primary key being a composite key of `ENTRY_ID` and `USER_ID` means that the pair can only exist once in the table (IE: 1, 1 won't allow 1, 1 to be added again).

Do not store counts in a table - use a VIEW for that so the number can be generated based on existing data at the time of execution.
It sounds like you want to guarantee that the set of comments is unique *with respect to* `username` X `post_id`. You can do this by using a unique constraint, or if your database system doesn't support that explicitly, with an index that does the same. Here's some SQL expressing that:

```
CREATE TABLE users (
    username VARCHAR(10) PRIMARY KEY,
    -- any other data ...
);

CREATE TABLE posts (
    post_id INTEGER PRIMARY KEY,
    -- any other data ...
);

CREATE TABLE comments (
    username VARCHAR(10) REFERENCES users(username),
    post_id INTEGER REFERENCES posts(post_id),
    -- any other data ...
    UNIQUE (username, post_id) -- Here's the important bit!
);

```