简体   繁体   中英

Count number of family members from one table for each rows in another table called house?

I have two MySQL tables, first, is house and second one family, The house table has two columns called house_id and house_name while the second table has three columns family_id, member_name the last column in the family table used to reference house_id from first table this is house_id

CONCEPT: How can get number of family_members with/who come from a certain house and put the counted number in the HTML table by fetching only on house table?

I created the following script to fetch from house,

SELECT * FROM house;

And I manipulated the fetched data using foreach like this,

    $mystmt = $db -> prepare('SELECT * FROM house');
    $mystmt->execute();
    $myresult = $mystmt->fetchAll();

    foreach($myresult as $mydata) {

        $myarray = array();         
        $myarray[] = $mydata['house_id'];
        $myarray[] = $mydata['house_name']; 
        $output[] = $myarray;

    }
    echo json_encode($output);

On the above code i get only two columns the house_id and house_name , Now how can i adjust this code to count from family table so that I can get another column called total_family_members

Just like this

family_id    | member_name   | house_id
    
    1        | John Jackson  | 1
    2        | Ketty Bebe    | 2
    3        | Maam Juke     | 1
    4        | Tike Nuke     | 2
    5        | Carol Michael | 2

Desired result

house_id | house_name | total_family_members

1        | Joh's house| 2

2        | kim's house| 3

In your example, two different processes are involved:

  1. Link everyone's house id to the house name. This can be achieved with a JOIN.
  2. Count the number of people in each house. This can be achieved with a GROUP BY and a COUNT.

Here is a solution:

SELECT house.house_id , house.house_name , COUNT( * ) AS total_family_members
FROM house 
INNER JOIN family ON family.house_id = house.house_id
GROUP BY family.house_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM