【问题标题】:mySQL select latest distinct rows from table [duplicate]mySQL从表中选择最新的不同行[重复]
【发布时间】:2020-06-27 21:39:26
【问题描述】:

我有这张桌子。

id  country     col1    col2    col3
1   country1    1   2   3
2   country1    2   2   1
3   country1    1   3   2
4   country2    3   2   2
5   country2    3   3   3
6   country3    3   2   2
7   country3    3   1   1

我正在尝试输出每个不同国家/地区的最后一行。

id  country     col1    col2    col3
3   country1    1   3   2
5   country2    3   3   3
7   country3    3   1   1

我尝试了各种解决方案,例如:

select distinct(country), col1, col2, col3 from ( SELECT country, col1, col2, col3 from tablename order by id DESC) a limit 1

但是,我无法获得所需的输出。

如何获取每个国家/地区的最新不同行?

谢谢!

【问题讨论】:

标签: mysql sql select subquery greatest-n-per-group


【解决方案1】:

您可以使用相关子查询进行过滤:

select t.*
from mytable t
where t.id = (select max(t1.id) from mytable t1 where t1.country = t.country)

【讨论】:

    【解决方案2】:

    使用此查询获取所有最后的 id 很简单:

    select max(id) from tablename group by country
    

    并使用它返回您想要的行:

    select * from tablename
    where id in (select max(id) from tablename group by country)
    

    或不存在:

    select t.* from tablename t
    where not exists (
      select 1 from tablename
      where country = t.country and id > t.id
    );
    

    请参阅demo。
    结果:

    > id | country  | col1 | col2 | col3
    > -: | :------- | ---: | ---: | ---:
    >  3 | country1 |    1 |    3 |    2
    >  5 | country2 |    3 |    3 |    3
    >  7 | country3 |    3 |    1 |    1
    

    【讨论】:

      【解决方案3】:

      在子查询中选择表和 WHERE 条件过滤器中的所有元素,在该子查询中只需按国家/地区分组:

       SELECT * 
       FROM tablename 
       WHERE id IN (SELECT MAX(id) FROM tablename  GROUP BY country)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-19
        • 2021-10-30
        • 1970-01-01
        • 2013-10-20
        • 1970-01-01
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        相关资源
        最近更新 更多