Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL count related records one query

Tags:

sql

mysql

count

So i have a mysql query that queries a table "contacts" each contact then has purchases. Purchases are in a related table. I want to display each contacts name with the number of purchases they have made to the right like this:

Adam(1)
Mike(8)
Steve(3) 

My current sql looks like this:

SELECT * FROM contacts ORDER BY contacts.name ASC"

and my current table looks like this:

Adam
Mike
Steve

In order to pull the count of the related (purchases) table into the current table i know i have to join the "purchases" table some how and then use the GROUP BY and count() function but i am not sure how to construct this sql statement. Can someone help me.

Again all i am trying to do is list a table (contacts) and count it's related records (purchases) and have it look like this:

Adam(1)
Mike(8)
Steve(3)

Thank you so much for any help.

like image 207
user982853 Avatar asked Dec 07 '11 02:12

user982853


2 Answers

Assuming the purchases table has a foreign key to the contacts table called contact_id, a query something like this should work:

SELECT c.name, count(p.contact_id)
FROM contacts AS c
LEFT OUTER JOIN purchases AS p
ON p.contact_id = c.contact_id
GROUP BY c.contact_id
ORDER BY c.name ASC

This query will put the count in a separate column, which I recommend. If you must format it the way you indicated with the parentheses after the name, you can use MySQL's concat() function. Something like this:

SELECT concat(c.name, '(', count(p.contact_id), ')') AS Name_And_Count_Together
FROM contacts AS c
LEFT OUTER JOIN purchases AS p
ON p.contact_id = c.contact_id
GROUP BY c.contact_id
ORDER BY c.name ASC
like image 191
Asaph Avatar answered Oct 25 '22 13:10

Asaph


  SELECT contacts.name, COUNT(*) 
    FROM contacts, purchases 
   WHERE contacts.name = purchases.name
GROUP BY purchases.key
ORDER BY contacts.name

Replace .name in the WHERE clause with the key you are using to identify records.

like image 21
kz3 Avatar answered Oct 25 '22 13:10

kz3