How to select shared values ​​from a column in MySQL?

Here is what I am using now:

$query = mysql_query(" SELECT vote_count FROM votes "); while ($row = mysql_fetch_array($query)) { $total_votes += $row['vote_count']; } echo $total_votes; 

Is there a more concise way, perhaps in the request itself without using a while loop?

+4
source share
2 answers

You can use the MySQL sum function and get the sum from MySQL itself:

 SELECT sum(vote_count) AS vote_count_sum FROM votes 

Get one line, which produces a request in $row and $row['vote_count_sum'] , will have the final value.

+5
source
 SELECT SUM( vote_count ) AS vote_summary FROM votes 
0
source

Source: https://habr.com/ru/post/1343511/


All Articles