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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With