SQL Group By和Limit问题

时间:2015-01-15 21:19:31

标签: mysql sql

我试过这个但是我似乎无法找到答案。假设我有两个表,一个称为线程,另一个称为注释。我的目标是根据某些条件选择线程(但将它们限制为总共3个),并且对于每个线程,将其与前3个注释(前5个由日期或其他列确定)连接。

我很难弄清楚如何限制注释的数量,因为在某些情况下,MySQL似乎存在LIMIT在子查询中的问题。

缩短架构:

thread: id, owner, creation_time
comment: id, thread_id, creation_time, display_time

以下是我现在的查询方式:

SELECT t.*, c1.*
FROM thread as t
JOIN comment c1 ON c1.thread_id = t.id
LEFT JOIN comment c2 ON c2.thread_id = c1.thread_id AND c2.display_time < c1.display_time
GROUP BY t.id, c1.id
HAVING COUNT(c2.id) < 3 and t.owner='test@test.com'
ORDER BY t.creation_time, c1.display_time

这是基于http://forums.mysql.com/read.php?20,128132,128134#msg-128134。但是,我需要限制返回的组的总数,并且添加LIMIT似乎只会导致语法错误。本质上,我想通过线程进行分页,但对于每个线程,最多有x个与之链接的注释

有谁知道如何做到这一点或有任何资源可以解释这一点?对于上下文,我使用的是MySQL 5.5。

线程的示例数据:

  | id  |     owner      |    creation_time    |
  |  1  |  test@test.com |  2014-06-07 03:45   |
  |  2  |  test@test.com |  2014-06-08 06:45   |
  |  3  |  test@test.com |  2014-06-09 07:53   |
  |  4  |  test@test.com |  2014-06-10 03:21   |
  |  5  |  test@test.com |  2014-06-11 11:27   |
  |  6  |  test@test.com |  2014-06-12 13:05   |

评论的示例数据:

  | id  |  thread_id  |  creation_time      |  display_time       |
  |  1  |      1      |  2014-06-07 03:45   |  2014-06-07 03:45   |
  |  2  |      1      |  2014-06-08 06:45   |  2014-06-07 03:45   |
  |  3  |      1      |  2014-06-09 07:53   |  2014-06-07 03:45   |
  |  4  |      1      |  2014-06-10 03:21   |  2014-06-07 03:45   |
  |  5  |      1      |  2014-06-11 11:27   |  2014-06-07 03:45   |
  |  7  |      2      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  8  |      2      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  9  |      2      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  10 |      2      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  11 |      3      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  12 |      4      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  13 |      4      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  14 |      4      |  2014-06-12 13:05   |  2014-06-07 03:45   |
  |  15 |      4      |  2014-06-12 13:05   |  2014-06-07 03:45   |

示例结果:

  | thread_id | comment_id | 
  |    1      |     1      |  
  |    1      |     2      |  
  |    1      |     3      |  
  |    2      |     7      |  
  |    2      |     8      |  
  |    2      |     9      |  
  |    3      |     11     |

1 个答案:

答案 0 :(得分:1)

希望有所帮助:

SELECT t.id, t.creation_time, c.id, c.creation_time
FROM (SELECT id, creation_time  
      FROM thread
      ORDER BY creation_time DESC
      LIMIT 5
     ) t
LEFT OUTER JOIN comment c ON c.thread_id = t.id
WHERE 3 >= (SELECT COUNT(1) 
            FROM comment c2 
            WHERE c.thread_id = c2.thread_id 
            AND c.creation_time <= c2.creation_time
           )

http://sqlfiddle.com/#!2/ae9d2b/10/0