Jump to content
kilnakorr

Counting rows in single query?

Recommended Posts

I can't seem to figure out how to count the rows for more than one thing in a single query (I know it must be possible :))

if I have a column called 'animal' how can I count the rows for value 'cat', 'dog', 'horse'?

eg.

number of rows for cat =10

number of rows for dog =12

number of rows for horse =25

Share this post


Link to post
Share on other sites

thanks.

It works as intended, but how can I distinct between the output?

I need to create a variable for each of the outputs, so I have to be able to output the count for just 'cat' ,'dog' and so on.

 

using a while loop will just output '10 12 15'

Share this post


Link to post
Share on other sites
10 minutes ago, kilnakorr said:

using a while loop will just output '10 12 15'

It will if you only out put the total column - but the animal type is there too...

mysql> CREATE TABLE myanimal (animal varchar(10) );
Query OK, 0 rows affected (0.55 sec)

mysql> INSERT INTO myanimal VALUES ('cat'),('dog'),('cat'),('dog'),('horse'),('horse'),('duck'),('dog'),('cat');
Query OK, 9 rows affected (0.06 sec)
Records: 9  Duplicates: 0  Warnings: 0

mysql> select * from myanimal;
+--------+
| animal |
+--------+
| cat    |
| dog    |
| cat    |
| dog    |
| horse  |
| horse  |
| duck   |
| dog    |
| cat    |
+--------+
9 rows in set (0.00 sec)

mysql> select animal
    ->      , count(*) as total
    -> FROM myanimal
    -> GROUP BY animal;
+--------+-------+
| animal | total |
+--------+-------+
| cat    |     3 |
| dog    |     3 |
| duck   |     1 |
| horse  |     2 |
+--------+-------+

In PHP...

$res = $db->query("SELECT animal
                        , COUNT(*) as total
                   FROM myanimal
                   GROUP BY animal
                  ");
$totals = [];
foreach ($res as $row) {
    $totals[ $row['animal'] ]  = $row['total'];
}

// now you can access each animal's total

echo $totals['horse'];          //--> 2 
echo $totals['dog'];            //--> 3 

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.