【问题标题】:Count the number of columns which are not null计算不为空的列数
【发布时间】:2013-05-10 02:56:37
【问题描述】:

房间:

+---------+---------+-----------+-------------+-------------+-------------+---------+
| room_id | room_no | room_stat | room_name   | player_a_id | player_b_id | turn_of |
+---------+---------+-----------+-------------+-------------+-------------+---------+
|       1 |       1 |         0 | blah        |           0 |           0 |       0 |
|       2 |       5 |         0 | second room |           1 |           3 |       0 |
|       3 |       3 |         0 | 3rd room    |           0 |           0 |       0 |
|       4 |       4 |         0 | 4th room    |           0 |           0 |       0 |
+---------+---------+-----------+-------------+-------------+-------------+---------+

我想计算房间里有多少玩家,例如:

  • 如果 player_a_id !=0 或 !NULL AND player_b_id !=0 或 !NULL 则 计数将是 2
  • 如果只有 player_a_id!=0 或 player_b_id!=0 那么 计数将是 1
  • 如果 player_a_id 和 player_b_id 都是 NULL 然后返回 0;

【问题讨论】:

    标签: mysql sql pdo


    【解决方案1】:

    我认为这是自MySQL 支持布尔运算以来最短的方法。

    SELECT  room_no,
            (player_a_id IS NOT NULL AND player_a_id <> 0) + 
            (player_b_id IS NOT NULL AND player_b_id <> 0) AS totalNumber
    FROM    room
    

    谢谢彼得 :)

    【讨论】:

    • 在您的查询sqlfiddle 中进行一次更正ORs 应该是ANDs
    【解决方案2】:

    你可以试试这样的:

    select room_id,
           ((case when player_a_id <> 0 and player_a_id is not null then 1 else 0 end) +
            (case when player_b_id <> 0 and player_b_id is not null then 1 else 0 end)
           ) as NumInRoom
    from room;
    

    与 NULL 的比较实际上是不必要的。以下具有相同的效果:

    select room_id,
           ((case when player_a_id <> 0 then 1 else 0 end) +
            (case when player_b_id <> 0 then 1 else 0 end)
           ) as NumInRoom
    from room;
    

    【讨论】:

    • 大多数答案都是正确的,但这个是第一个,也是我现在使用的。 :)
    【解决方案3】:
    select
       room_id, 
       (least(coalesce(player_a_id, 0), 1) + least(coalesce(player_b_id, 0), 1)) 
        as player_count
    from room;
    

    coalesce 选择其列表中的第一个非 NULL 条目,因此它将得出实际的玩家 ID,如果为 NULL,则为 0。

    least 选择合并值中的最小值,因此任何玩家 ID > 1 将仅计为 1。

    将这两者相加,您就有了该房间的非 0、非 NULL 玩家数。

    【讨论】:

      【解决方案4】:

      您可以通过考虑id 而不是不是的值来大大简化:

      select 2
        - ifnull(player_a_id = 0, 1)
        - ifnull(player_b_id = 0, 1)
      from room
      

      this in SQLFiddle

      这个查询使用了测试的否定,当为真时减去

      请注意,在 mysql 中,true1false0 允许您简单地添加测试数字而不是使用案例语句将测试转换为数字在我熟悉的所有其他数据库中都需要。

      【讨论】:

      • 如果player_a_idplayer_b_id 为空怎么办?
      • @JW웃 好的 - 你找到我了 :) 我已经修复它并创建了一个小提琴。谢谢 - 我会记住那个错误。干杯。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 2021-09-18
      • 1970-01-01
      相关资源
      最近更新 更多