Ayub
Ayub

Reputation: 875

How should I store multiple values into an SQL row?

I have a table called users, and one of the rows needs to hold all the actions the user did, and the actions are referenced as action_ids.

How do I have the row hold multiple action_ids?

For example, lets say the user did 5 actions, each with IDs 100001, 100002, 100003, 100004, 100005. How do I store that into the database so I can later say all the actions a user did?

The row might have to store hundreds or thousands of 6 digit values.

Upvotes: 1

Views: 1049

Answers (1)

Adam Wenger
Adam Wenger

Reputation: 17570

I would recommend you create a UserAction table with a UserId and ActionId. This way you could reference the actions done without having to store multiple values in one row of your users table.

You would store rows for each action a user takes. The table might look like this:

SELECT ua.UserId, ua.ActionId
FROM UserAction AS ua
ORDER BY ua.UserId ASC, ua.ActionId ASC
LIMIT 5

Results:

1, 100001
1, 100002
1, 100007
2, 100002
2, 100003

Meaning that UserId = 1 performed actions 100001, 100002 and 100007 and UserId 2 performed 100002 and 100003

Doing this also helps preserve normalization for your database, making future queries easier as well.

You will be able to find how many actions have been performed by users easier (and other tasks) with this structure than parsing a column with text/string values: (I'm assuming you have a Name, or similar field)

SELECT u.Name, COUNT(1) AS NumberOfActionsPerformed
FROM users AS u
INNER JOIN UserAction AS ua ON u.userId = ua.UserId
GROUP BY u.userId, u.Name 
ORDER BY NumberOfActionsPerformed DESC

Also, if I were making the table, I would add UserActionId as an Auto-incremental Id column to use as my Primary Key

Upvotes: 6

Related Questions