I have two tables, users and visits. I want to select all users who have ‘active’ in the visits table’s status field, with a count of all visit records regardless of active/inactive status.
This query would only give me a count of ‘active’ visit records
SELECT
users.user_id,
COUNT(visits.id)
FROM users u
JOIN visits v ON v.user_id=u.user_id
WHERE visits.status='active'
I was thinking of a subquery, or a php loop but worried about performance if the users table grows. If subquery’s the best solution please post the active record code.
A sub-query will be more efficient than looping in the code. I’d suggest this query:
And if you need only user_id and no users.* field, then you don’t have to join to users table (inspired by answer from arunmoezhi):
Edited for formatting.