Daniel H
Daniel H

Reputation: 2925

Using mysql COUNT to count multiple columns

I have information in a table like so:

id    name    recommender
 1    daniel  steve
 2    daniel  tony
 3    steve   daniel

and this code:

<h2>Follow/Join Recommendation League Table</h2>
<br/>
<?php

$query = "SELECT name_of_follower, COUNT(name) FROM recommendation_competition_entrants GROUP BY name_of_follower ORDER BY COUNT(name) DESC"; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
        echo $row['name_of_follower'] . " has ". $row['COUNT(name)'] . " entries.";
        echo "<br />";
}

?>

This counts all entries in the 'name' column and displays a mini league table which looks like this:

daniel - 2 entries
steve - 1 entry

What I need to do now is count names from both the name & recommender columns so the table would look like this:

daniel - 3 entries
steve - 2 entries
tony - 1 entry

Is there a simple way to do this?

Thanks for any help

Upvotes: 0

Views: 4606

Answers (2)

Ujjwal Manandhar
Ujjwal Manandhar

Reputation: 2244

select name_of_follower, 
       count(name_of_follower) 
  from ( select name as name_of_follower 
          from abc 
         union all 
        select follower as name_of_follower  
          from abc
       ) t
 group by t.name_of_follower 
 order by count(name_of_follower) desc

Upvotes: 1

Dheeraj Kumar
Dheeraj Kumar

Reputation: 1008

SELECT SUM(COUNT(name) + COUNT(recommender)) FROM...

Upvotes: 0

Related Questions