MySQL:具有最小日期的唯一行

时间:2012-06-13 07:29:04

标签: mysql sql filter

想象一下,我有以下表格:

NAME DATE OTHER_CONTANT

'A' '2012-06-05' 'baz'
'A' '2012-06-04' 'bar'
'B' '2012-06-05' 'foo'
'C' '2012-06-05' 'bla'
'C' '2012-06-04' 'blah'
'C' '2012-06-06' 'bleh'

现在我想过滤此表,只包含具有唯一NAME和最早日期的行:

'A' '2012-06-04' 'bar'
'B' '2012-06-05' 'foo'
'C' '2012-06-04' 'blah'

我正在考虑使用GROUP BY语句但是使用GROUP BY我只能获得一列结果,我想获得整行。有关如何进行此过滤的任何建议吗?

5 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

select m.name, m.date, m.other_constant 
  from mytable m
  join (select name, min(date) min_date from mytable group by name) n
    on m.name = n.name and m.date = n.min_date

另请参阅SQLfiddle

答案 1 :(得分:2)

以下SQL创建所有不同名称的列表。然后,对于每个名称,它会查找具有最新日期的条目。

select  *
from    (
        select  distinct name
        from    YourTable
        ) names
join    YourTable yt1
on      yt1.name = names.name
        and yt1.date =
        (
        select  date
        from    YourTable yt2
        where   yt2.name = yt1.name
        order by
                date
        limit   1
        )

Live example using beny23's SQL Fiddle.

答案 2 :(得分:1)

两个查询都完美无缺。

SELECT * 
FROM   MyTable a 
       INNER JOIN (SELECT name, 
                          Min(date) AS date 
                   FROM   MyTable 
                   GROUP  BY name) b 
               ON a.name = b.name 
                  AND a.date = b.date

SELECT a.* 
FROM   mytable a 
       LEFT JOIN mytable b 
              ON a.name = b.name
                 AND a.date > b.date 
WHERE  b.name IS NULL 

答案 3 :(得分:0)

select *
from (
   select name, min(date) as mindate, other_contact
   from table_name group by name
   ) as x
   inner join table_name as f 
   on f.name = x.name and f.date= x.mindate; 

答案 4 :(得分:0)

SELECT
    a.name,
    a.date,
    b.other_contant
FROM
    (
        SELECT
            name,
            MIN(date) AS date,
        FROM
            yourtable
        GROUP BY 
            name
    ) a
INNER JOIN
    yourtable b ON a.name = b.name AND a.date = b.date