如何组合重复行只返回重复数据的单个实例?

时间:2013-08-08 17:42:17

标签: mysql

我有一个看起来像这样的表:

ID  | Time  | Metadata
======================
1   | 01:00 | Foo
2   | 02:00 | Foo
3   | 03:00 | Foo
4   | 04:00 | Bar
5   | 05:00 | Bar
6   | 06:00 | Bar
7   | 07:00 | Foo
8   | 08:00 | Foo
9   | 09:00 | Foo
10  | 10:00 | Foo
11  | 11:00 | Foo
12  | 12:00 | Foo

我想让所有元数据的第一个实例发生变化,例如:

ID  | Time  | Metadata
======================
1   | 01:00 | Foo
4   | 04:00 | Bar
7   | 07:00 | Foo

GROUP BY会将第1行和第7行组合在一起,这不是我想要的。我可以在SQL之外做,但这需要相当大的数据选择,我想避免。

3 个答案:

答案 0 :(得分:0)

我认为最简单的方法是创建一个存储过程并在其中执行“元数据更改”逻辑。存储过程会将光标返回到您需要的集合。 这样,您就不会向客户端提取大量数据并在客户端上进行处理。

答案 1 :(得分:0)

select t11.*
from test1 t11
where 
t11.metadata <> (select t12.metadata from test1 t12
                 where t11.id > t12.id
                 order by t12.id desc
                 limit 1
                )
or not exists (select 1 from test1 t13
               where t11.id > t13.id)
order by id

演示HERE

答案 2 :(得分:0)

另一种方法

SELECT id, `time`, metadata
FROM 
(select @cnt := 0, @previous := '' from dual) dummy
join (

  SELECT  id, `time`,
      metadata, @cnt := IF(metadata = @previous, @cnt + 1, 1) occurence,
      @previous := metadata FROM trytable

) a where occurence = 1;

Demo Here

相关问题