【问题标题】:Count number of rows with one value and rows with another value, and output lowest appearing value in table计算具有一个值的行数和具有另一个值的行数,并输出表中出现的最低值
【发布时间】:2023-03-23 12:58:01
【问题描述】:

我想知道是否可以计算 MySQL 表中包含 pet 列中值 Cat 的行数,并计算同一表中包含 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

所以它应该响应猫、狗、马或蛇,具体取决于哪个宠物的行数最少。

【问题讨论】:

  • 我认为你需要分享一些代码。
  • 当然有可能:)
  • @BasicBridge 我用一些代码编辑了我的帖子。

标签: php mysql


【解决方案1】:

你可以明确地使用mysql中的COUNT()函数并让php比较值。

【讨论】:

  • 我想过这样做,但我想我可以通过使用一个 MySQL 查询来缩短代码。
【解决方案2】:
SELECT pet, COUNT(pet)
FROM yourtable
WHERE pet IN ('Dog', 'Cat')
GROUP BY pet

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

      【解决方案4】:

      从表pets 中选择猫和狗,将它们分组并计算每个组的成员。然后选择最上面的组。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-24
        • 1970-01-01
        相关资源
        最近更新 更多