【问题标题】:Common values from the same table in MySQLMySQL中同一张表的共同值
【发布时间】:2020-12-18 11:37:51
【问题描述】:

我有一张表作为 PCity,其中有 2 个属性,如下所示: 我正在使用 MySQL。

City    Year
A   2017
B   2017
C   2017
A   2018
B   2018
C   2018
A   2019
B   2019
C   2019
A   2020
B   2020
D   2020
E   2020
F   2020

我只想得到那些多年来一直存在的城市:

City    Year
A   2017
B   2017
A   2018
B   2018
A   2019
B   2019
A   2020
B   2020

【问题讨论】:

    标签: mysql join self-join


    【解决方案1】:

    这是使用窗口函数的一种选择:

    select *
    from (
        select t.*, count(*) over(partition by city) cnt
        from mytable t
    ) t
    where cnt = (select count(distinct year) from mytable)
    

    这需要 MySQL 8.0。在早期版本中,一种替代方法使用子查询:

    select *
    from mytable t
    where (select count(*) from mytable t1 where t1.city = t.city)
        = (select count(distinct year) from mytable)
    

    如果表中有重复项(与您的示例数据显示的不同),您将在第一个子查询中使用 count(distinct year) 而不是 count(*)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多