简体   繁体   English

协助进行复杂的MySQL查询(使用LIMIT吗?)

[英]Assistance with complex MySQL query (using LIMIT ?)

I wonder if anyone could help with a MySQL query I am trying to write to return relevant results. 我想知道是否有人可以帮助我尝试编写MySQL查询以返回相关结果。

I have a big table of change log data, and I want to retrieve a number of record 'groups'. 我有一个很大的变更日志数据表,我想检索许多记录“组”。 For example, in this case a group would be where two or more records are entered with the same timestamp. 例如,在这种情况下,一个组将是两个或两个以上具有相同时间戳记的记录的输入。

Here is a sample table. 这是一个示例表。

==============================================
ID     DATA                         TIMESTAMP
==============================================
1      Some text                    1379000000
2      Something                    1379011111
3      More data                    1379011111
3      Interesting data             1379022222
3      Fascinating text             1379033333

If I wanted the first two grouped sets, I could use LIMIT 0,2 but this would miss the third record. 如果我想要前两个分组集,则可以使用LIMIT 0,2但这会丢失第三条记录。 The ideal query would return three rows (as two rows have the same timestamp). 理想查询将返回三行(因为两行具有相同的时间戳记)。

==============================================
ID     DATA                         TIMESTAMP
==============================================
1      Some text                    1379000000
2      Something                    1379011111
3      More data                    1379011111

Currently I've been using PHP to process the entire table, which mostly works, but for a table of 1000+ records, this is not very efficient on memory usage! 目前,我一直在使用PHP处理整个表,该表大部分都可以工作,但是对于1000多个记录的表,这在内存使用方面不是很有效!

Many thanks in advance for any help you can give... 在此先感谢您提供的任何帮助...

Get the timestamps for the filtering using a join . 使用join获取用于过滤的时间戳。 For instance, the following would make sure that the second timestamp is in a completed group: 例如,以下操作将确保第二个时间戳在完整的组中:

select t.*
from t join
     (select timestamp
      from t
      order by timestamp
      limit 2
     ) tt
     on t.timestamp = tt.timestamp;

The following would get the first three groups, no matter what their size: 以下内容将获得前三组,无论它们的大小如何:

select t.*
from t join
     (select distinct timestamp
      from t
      order by timestamp
      limit 3
     ) tt
     on t.timestamp = tt.timestamp;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM