0

I want to select from a mysql table and return the most popular string in a column

for example, if i have 6 rows and a column called producttype

producttype = 'One'
producttype = 'One'
producttype = 'Two'
producttype = 'Three'
producttype = 'Three'
producttype = 'Three'

it will return the string Three because there is more rows of that than anything else

2 Answers2

3
select producttype 
from your_table
group by producttype 
order by count(*) desc
limit 1

If you group by the producttype then you can use count() to determine the count of each group. Order by that and take only the first record.

juergen d
  • 201,996
  • 37
  • 293
  • 362
0

I guess you don't know how to make the DB connection and all so here is a full example:

<?php
    $db = mysql_connect($host, $DB_User, $DB_Pass);
    if(!$db){
        echo "Failed to connect to MySQL: " . mysql_connect_error();
        die;

    }

$query = "Select * "
        ."FROM my_table"
        ."GROUP BY producttype "
        ."ORDER BY COUNT(*) DESC"
        ."LIMIT 1";

$result = mysqli_query($db, $query);

$result = mysqli_query($con,"SELECT * FROM Persons");

$row = mysql_fetch_array($result);
if($row){
  echo 'most common type is: ' . $row['producttype'];
}

mysqli_close($db);
d.raev
  • 9,216
  • 8
  • 58
  • 79