phpmyadmin 查询数据库表

esyap4oy  于 2022-11-09  发布在  PHP
关注(0)|答案(2)|浏览(234)

我有一张牌桌,我可以在上面为玩家保存特定游戏的玩法。
游戏具有不同的级别。
玩家可以多次玩同一级别。
我需要查询该表来计算特定玩家在特定日期内第一次玩的级别数。

**例如,**在我的图片中,我需要知道ID = 267的玩家在日期“2022-09-01”上的新级别。

查询结果应该是1级,因为玩家在该特定日期之前已经玩过1级和2级。

+----+-----------+---------+----------+-------+---------------------+---------------------+    
| id | player_id | game_id | level_id | score | created_at          | updated_at          |  
+----+-----------+---------+----------+-------+---------------------+---------------------+  
|  1 |       267 |      11 |        1 |   350 | 2022-08-28 00:28:52 | 2022-08-28 00:28:52 |  
|  2 |       267 |      11 |        2 |   150 | 2022-08-28 00:32:52 | 2022-08-28 00:32:52 |  
|  3 |       267 |      11 |        1 |   175 | 2022-09-01 00:28:52 | 2022-09-01 00:28:52 |  
|  4 |       267 |      11 |        2 |   125 | 2022-09-01 00:32:52 | 2022-09-01 00:32:52 |  
|  5 |       267 |      11 |        3 |   115 | 2022-09-01 00:35:52 | 2022-09-01 00:35:52 |  
+----+-----------+---------+----------+-------+---------------------+---------------------+

balp4ylt

balp4ylt1#

下面是一个原始的MySQL查询,应该可以工作:

SELECT game_id, COUNT(*) AS cnt
FROM yourTable t1
WHERE player_id = 267 AND
      DATE(t1.created_at) = '2022-09-01' AND
      NOT EXISTS (
          SELECT 1
          FROM yourTable t2
          WHERE t2.game_id = t1.game_id       AND
                t2.player_id = t1.player_id   AND
                t2.created_at < t1.created_at AND
                t2.level_id = t1.level_id
      )
GROUP BY game_id;

该查询对每个玩家267记录进行计数,对于该玩家267记录,我们 * 不能 * 找到具有相同级别的同一玩家的更早记录。

0wi1tuuw

0wi1tuuw2#

使用条件聚合:

SELECT game_id,
       COUNT(DISTINCT CASE WHEN DATE(created_at) <= '2022-09-01' THEN level_id END) - 
       COUNT(DISTINCT CASE WHEN DATE(created_at) < '2022-09-01' THEN level_id END) count
FROM tablename
WHERE player_id = 267
GROUP BY game_id;

或:

SELECT game_id,
       COUNT(DISTINCT level_id) - 
       COUNT(DISTINCT CASE WHEN DATE(created_at) < '2022-09-01' THEN level_id END) count
FROM tablename
WHERE player_id = 267 AND DATE(created_at) <= '2022-09-01'
GROUP BY game_id;

请参阅demo

相关问题