简体   繁体   中英

Count number of rows with one value and rows with another value, and output lowest appearing value in table

I was wondering if it was possible to count the number of rows in a MySQL table that contains the value Cat in the column pet and count the number of rows in the same table that contains the value Dog in the column pet. And compare the number of rows each query returns and output 'Cat' if the rows containing Cat are less than the rows containing 'Dog' and vice versa.

EDIT: Here is an example of what I want.

$pet = mysql_query("SELECT squad, COUNT(pet) FROM mytable WHERE pet IN ('cat', 'dog', 'horse', 'snake') GROUP BY pet ORDER BY COUNT(pet) DESC LIMIT 1") or die(mysql_error());
echo $pet; // this should output the pet with the lowest number of rows

So it should echo either cat, dog, horse or snake depending on which pet has the lowest amount of rows.

您可以使用mysql中的COUNT()函数定义地执行此操作,并让php比较这些值。

SELECT pet, COUNT(pet)
FROM yourtable
WHERE pet IN ('Dog', 'Cat')
GROUP BY pet
select case 
        when CatCount > DogCount then 'Cat' 
        when CatCount < DogCount then 'Dog'
    end 
from (
    select count(case when pet = 'Cat' then 1 end) as CatCount,
        count(case when pet = 'Dog' then 1 end) as DogCount
    from MyTable
) a

From table pets selects cats and dogs, groups them and counts members of each group. Then selects the top group.

SELECT pet, COUNT(pet)
FROM pets
WHERE pet IN ('Cat', 'Dog')
GROUP BY pet
ORDER BY COUNT(pet)
LIMIT 1

This can be easily extended to more types of pet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM