Our company is trying to find a good generic way to have Many-to-One data for an entity. For example, a user might have 1 primary email, but many other emails also attached to their account.
So we have a users table (1 row maps to 1 user):
| id | handle | primary_email | is_verified | first_name | last_name |
|--------|----------|---------------|-------------|------------|-----------|
| (int) | (string) | (string) | (boolean) | (string) | (string) |
but then we may want to store multiple emails for the same user, so we have another table, let's called it "users_map", where many rows map to 1 user:
| id | user_id | key | value |
|--------|---------|----------|--------|
| (int) | (uuid) | (string) | (json) |
so for example if there were multiple emails for the same user, we would do something like this:
| id | user_id | key | value |
|----|---------|-------|------------------|
| 1 | 1 | email | "[email protected]" |
| 2 | 1 | email | "[email protected]" |
| 3 | 1 | email | "[email protected]" |
| 4 | 2 | email | "[email protected]" |
| 5 | 2 | email | "[email protected]" |
so my question is - is there a better way to do this other than using JSON for the value column? If not - is there a way to enforce a schema on the JSON somehow? Last question - from my brief research the inverse table design is called an "unpivot" table - but if there is a better name for it please let me know.
The potential advantage of a generic table by user? if you shard by user, each shard has only 2 tables instead of 5 or 10?
user_emails
table instead of auser_map
table and there would be nokey
column, just avalue
column that would probably be titled "email"