Mysql – Creating optimized table without duplicates in MySQL

database-designMySQLnormalization

I am struggling to create a table with a structure that shows values of user-date relation.
Sample pseudo-database:

+------+----------+----------+----------+-----
| user | 01012016 | 02012016 | 03012016 | ...
+------+----------+----------+----------+-----
| 1    | 2        | 57       | ...      | ...
| 2    | 12       | 73793    | ...      | ...
| 3    | 56       | 468      | ...      | ...
| 4    | 1689     | 12357    | ...      | ...
| 5    | 946      | 13       | ...      | ...
+------+----------+----------+----------+-----

Values are integer.

According to MySQL Reference Manual, key range is limited.

What structure a table should have to allow unlimited amount of columns and rows in this case?

I am aware that I can create a separate table for each user, but the idea is to keep everything optimized – in a smallest possible number of tables.

I am also aware of a simple structure (user, date, value), but there will be a lot duplicates, to be specific, in 'user' and 'date' columns:

+------+----------+----------+
| user | date     | value    |
+------+----------+----------+
| 1    | 01012016 | 57       |
| 1    | 02012016 | 73793    |
| 1    | 03012016 | 468      |
| 2    | 01012016 | 12357    |
| 2    | 02012016 | 13       |
| 2    | 03012016 | 618      |
| ...  | ...      | ...      |
+------+----------+----------+

And even if I decide to use this structure, what key should I define a primary one?

Best Answer

Your second method is the right way to represent the data in the database.

If you want a user/date pair to appear only once, then create a unique index/constraint to enforce this:

create unique index unq_simplestructure_user_date on simplestructure(user, date);

Tables in SQL have a pre-defined structure. Database systems (for better or worse) are not designed to hold arbitrary numbers of columns. In cases where this is a requirement (and your problem is not one of these cases), then a JSON representation (or something similar) can be used.