Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select count using sub-select in sql?

I’m trying to get a count of an inner join. Should I use a sub-select?

const users = db.queryEntries(
  "SELECT username, created_at, email, phone FROM users WHERE contactme = 1 ORDER BY created_at DESC"
);

There’s another table called searches that has a user_id attribute. I want to get the number of searches for each user returned in the first query.

Would be something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT count(*) as total
FROM searches
WHERE searches.user_id = user.id

…such that the first query will return total for each user

>Solution :

if I understand correctly, you can try to use COUNT with GROUP BY in subquery, then do JOIN by userid

SELECT u.username, u.created_at, u.email, u.phone ,s.total
FROM users u
INNER JOIN (
    SELECT count(*) as total,user_id
    FROM searches 
    GROUP BY user_id
) s ON s.user_id = u.id
WHERE u.contactme = 1 
ORDER BY u.created_at DESC
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading