Yes, you can do both in the same query
SELECT cf.*, count(cm.messages_id) AS total
FROM contacts_folders cf left outer join
contacts_messages cm
on cf.id = cm.folders_id and
cm.status = '1' AND cm.mark = '0' left outer join
contacts_basics cb
on cb.contacts_id = cm.contacts_id
group by cf.folders_id
order by cf.sort_order, cf.name;
This uses a left outer join
to be sure that you get all folders, even if there are no messages (which is how the original code works). Because of the left outer join
, the conditions need to be moved into on
clauses.
It also fetches all the information from the folders as well as the total. If there are no messages, then it should return 0 for that folder.