Using mysql COUNT to count multiple columns

情到浓时终转凉″ 提交于 2020-01-25 06:42:09

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/5743263/using-mysql-count-to-count-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!