MySQL递归查询取决于结果

时间:2016-12-03 08:59:52

标签: mysql

我有游戏桌。

id  |  team1   | team2  |  score1  |  score2  |  date
 1     Hawks     Ducks          1          2     2016-12-02
 2     Sharks    Flyers         3          0     2016-12-02
 3     Kings     Oilers         1          3     2016-12-03
 4     Leafs     Stars          4          3     2016-12-03
 5     Blues     Jets           2          5     2016-12-04
 ..    ..        ..            ..         ..     ..

我需要至少10场比赛。如何编写MySQL查询,如下所示:

SELECT * FROM games
WHERE date > NOW() - INTERVAL 1 DAY
  AND date < NOW() + INTERVAL 1 DAY

如果此查询的结果少于10行,则

SELECT * FROM games
WHERE date > NOW() - INTERVAL 2 DAY
  AND date < NOW() + INTERVAL 2 DAY

如果此查询的结果少于10行,则

SELECT * FROM games
WHERE date > NOW() - INTERVAL 3 DAY
  AND date < NOW() + INTERVAL 3 DAY

等...

为什么这样?有时一周没有任何游戏,有时候每天都有很多游戏。

我只想在一个MySQL查询中编写它。

2 个答案:

答案 0 :(得分:1)

SELECT * , ABS(TIMESTAMPDIFF(DAY, date_of_game , NOW())) as 'diff_days'
FROM games 
ORDER BY diff_days
LIMIT 10

我已重命名您的日期列,因为日期是MySQL中的保留字。

我创建了一个sqlfiddle,您可以在其中检查代码的行为:

http://sqlfiddle.com/#!9/33c381d/6

答案 1 :(得分:0)

给这个机会:你可以在区间N DAY

中选择你想要查看的天数
SELECT * from (
SELECT g.*, (
    SELECT `date`
    FROM (
        select `date`,count(*) as cnt from games
        WHERE `date` > DATE(now() - interval 3 DAY)
        GROUP BY `date`
        HAVING cnt >= 10
        ORDER BY `date` DESC, count(*)
        LIMIT 1
    ) as tmp ) selected_day
FROM games g
) as total
WHERE `date` = selected_day;

<强>样品

mysql> SELECT * from (
    -> SELECT g.*, (
    ->     SELECT `date`
    ->     FROM (
    ->         select `date`,count(*) as cnt from games
    ->         WHERE `date` > DATE(now() - interval 3 DAY)
    ->         GROUP BY `date`
    ->         HAVING cnt >= 10
    ->         ORDER BY count(*), `date` DESC
    ->         LIMIT 1
    ->     ) as tmp ) selected_day
    -> FROM games g
    -> ) as total
    -> WHERE `date` = selected_day;
+----+--------+------------+--------------+
| id | name   | date       | selected_day |
+----+--------+------------+--------------+
|  9 | game 1 | 2016-12-03 | 2016-12-03   |
| 10 | game 1 | 2016-12-03 | 2016-12-03   |
| 11 | game 1 | 2016-12-03 | 2016-12-03   |
| 12 | game 1 | 2016-12-03 | 2016-12-03   |
| 13 | game 1 | 2016-12-03 | 2016-12-03   |
| 14 | game 1 | 2016-12-03 | 2016-12-03   |
| 15 | game 1 | 2016-12-03 | 2016-12-03   |
| 16 | game 1 | 2016-12-03 | 2016-12-03   |
| 17 | game 1 | 2016-12-03 | 2016-12-03   |
| 18 | game 1 | 2016-12-03 | 2016-12-03   |
+----+--------+------------+--------------+
10 rows in set (0,00 sec)

子查询将获得10行或更多行的日期:

mysql>         select `date`,count(*) as cnt from games
    ->         WHERE `date` > DATE(now() - interval 3 DAY)
    ->         GROUP BY `date`
    ->         HAVING cnt >= 10
    ->         ORDER BY count(*), `date` DESC
    ->         LIMIT 1
    -> ;
+------------+-----+
| date       | cnt |
+------------+-----+
| 2016-12-03 |  10 |
+------------+-----+
1 row in set (0,00 sec)

mysql>