Got 2 tables - contacts and messages:
contact_id | contact_email
1 | some@mail.com
2 | other@mail.com
3 | no@nono.com
message_id | message_recipients
1 | 1,2,3
2 | 3
message_recipients
field contains ID(s) of contact(s) message was assigned to. Each message can have one or more IDs assigned, so they are separated by ,
symbol.
I need to show all contacts, and count of messages are assigned to each contact. Since message_recipients
field may contain multiple IDs, I can't run a query like SELECT * FROM contacts, messages WHERE contacts.contact_id=messages.message_recipients
because it won't work properly.
If I run SELECT * FROM contacts FULL JOIN messages
, it returns many duplicated rows from contacts
table. Sure thing, I can run SELECT * FROM contacts FULL JOIN messages GROUP BY contact_id
, but this one returns only 1st message from messages
table.
I know that in order to count how many messages each contact has assigned to, I will probably need to explode message_recipients
field from each row into array and use code like if (in_array($contact_id, $message_recipients_array)) {$total++;}
or similar. Now my main concern is how to all I need by writing as simple query as possible.