计算具有一个值的行数和具有另一个值的行,并在表中输出最低的出现值

时间:2014-02-03 20:10:59

标签: php mysql

我想知道是否可以计算MySQL表中包含cat pet中值Cat的行数,并计算同一个表中包含pet pet中值Dog的行数。并比较每个查询返回的行数,如果包含Cat的行小于包含'Dog'的行,则输出'Cat'。反之亦然。

编辑:以下是我想要的示例。

$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

所以它应该回应猫,狗,马或蛇,这取决于哪只宠物行数最少。

4 个答案:

答案 0 :(得分:0)

你可以使用mysql中的COUNT()函数定义它,并让php比较这些值。

答案 1 :(得分:0)

SELECT pet, COUNT(pet)
FROM yourtable
WHERE pet IN ('Dog', 'Cat')
GROUP BY pet

答案 2 :(得分:0)

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

答案 3 :(得分:0)

从表pets中选择猫和狗,对它们进行分组并计算每组的成员。然后选择顶部组。

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

这可以很容易地扩展到更多类型的宠物。