MySQL counts the same rows

An example of MySQL column data:

stringone
stringthree
stringtwo
stringone
stringone
stringthree

How can I get the following result from MySQL using PHP or mysql_? I do not know the contents of the lines.

stringone    3x
stringthree  2x
stringtwo    1x

Thanks for your suggestions and guidance.

+4
source share
4 answers

try the following:

SELECT columnname1,count(columnname1) 
  FROM tablename 
   GROUP BY conlumnname1;

http://sqlfiddle.com/#!2/ecc99/1

+5
source
 SELECT string, COUNT(1) FROM table GROUP BY string
+3
source

PHP-

array_count_values() .

, , .

, $resultfromSQL = array('stringone','stringthree','stringtwo','stringone','stringone','stringthree'); SELECT..

$resultfromSQL = array_count_values($resultfromSQL);
//Since you need the **x** multiplier , you can do an `array_walk()`
array_walk($resultfromSQL,function (&$v){ $v=$v.'x';});

OUTPUT :

Array
(
    [stringone] => 3x
    [stringthree] => 2x
    [stringtwo] => 1x
)

+1

, group by . i, ( , ):

select string_col, count(1) as num
from table
group by string_col
order by num desc
+1

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


All Articles