It would be best to normalize your database as follows:
Table users: (user_id, name, email) Table messages: (user_id, msg_number, msg_code)
The users table would have user_id as the primary key, and the messages table would have a composite primary key at (user_id, msg_number) . The msg_number field will represent message number 1-4 (the number you specified in the column names).
The composite primary key ensures that each user can have only one message for each msg_number . You can also create a check constraint so that msg_number always <= 4. Finally, you can define user_id in the messages table as a foreign key in the users table.
Note that if the user did not send the message, you should not have a row in the message table with msg_code = 0. Instead, you should simply omit the row.
With normalized tables, counting the number of messages for each user will be as simple as:
SELECT u.name, COUNT(m.msg_number) as num_of_messages FROM users u JOIN messages m ON (m.user_id = u.user_id) GROUP BY u.user_id;
source share