2

I am trying to achieve a strange query. I have a table like this:

table People

-----------------------
| id | name | family |
+----+------+--------+
| 1  |  Bob |  Smith |
+----+------+--------+
| 2  |  Joe | Smith  |
----------------------

I want to return an assoc array like this

id : 1
name : bob
family : smith
familySize : 2

So something like this

"SELECT id, name, family, familySize FROM People"

How can I get the familySize in there? Keep in mind my query may have many families and I want them all to be returned.

Thank you.

1
  • 4
    Use MySQL's COUNT() aggregate function. Commented Oct 30, 2014 at 4:20

4 Answers 4

3

The above 2 answers won't work with multiple families.

You can do something like this:

SELECT id, name, family, familySize FROM People p1
JOIN (SELECT COUNT(*) as familySize, family FROM People GROUP BY family) p2
USING(family)
Sign up to request clarification or add additional context in comments.

9 Comments

"The above 2 answers won't work with multiple families." - I don't think yours will neither. I doubt OP has a column called familySize.
My answer doesn't expect a column called familySize.
What do you call this then SELECT id, name, family, familySize <=?
Believe me, I have. What is it that I'm not grasping?
JOIN (aka INNER JOIN) requires results in both tables, so when joining to itself you know for certain there are results. LEFT JOIN will return the first result even if there are no results on the subsequent query; I hope that makes sense, I'm having trouble wording it.
|
1

You can do it like this

SELECT id, name, family, count(id) as familySize FROM People

Comments

1
     "SELECT id, name, family, count(family) as familySize FROM People group by   
      family"

1 Comment

I don't think OP has a column called familySize
1

I would like to mention here that what if two or three families have the same surname "Smith". It won't give you the desired results.

What I suggest you is while inserting the data in the table assign a family head and all the family members have a field called family_ID has primary key as value of family_head.

This will give you accurate results with 1000's of people. I have made a family portal has over 12k members now and it works fine for me.

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.