MYSQL count related records one query?

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

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.

1 Thank you so much, that worked like a charm. Glad I posted in here bc I would have never figured that out on my own. Thank you again.

– user982853 Dec 7 at 3:46.

The required query would be something like this (I don't know your schema): SELECT c. Name, count(p. Id) FROM contacts c JOIN purchases p ON (c.Id = p.

Id) GROUP BY p. Id ORDER BY contacts.Name ASC.

1 An outer join would be advisable so that you can include contacts with zero purchases too. – Asaph Dec 7 at 2:56 1 Yep, you are right – z-index Dec 7 at 3:09.

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.

An outer join would be advisable so that you can include contacts with zero purchases too. – Asaph Dec 7 at 2:57 1 Ah, good point thank you – Kyle Banks Dec 7 at 3:00.

The required query would be something like this (I don't know your schema).

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions