How to select multiple rows by multi-column primary key in MySQL?

前端 未结 2 1315
梦毁少年i
梦毁少年i 2021-02-04 16:11

I have a table with a multi-column primary key (city/state/date) and many more columns of data. I\'m looking to get the latest data for each city/state. How do I do that cleanly

相关标签:
2条回答
  • 2021-02-04 16:21

    MySQL supports tuple comparisons:

    SELECT * FROM data WHERE 
     (state, city, date) IN (
      ('CA', 'San Francisco', '2013-09-01'), 
      ('CA', 'Los Angeles', '2013-08-01'), 
      ('NY', 'New York', '2013-10-01'));
    
    0 讨论(0)
  • 2021-02-04 16:23

    I think this should do the trick for you:

    select 
        * 
    from 
        data t1
    natural join 
        ( 
            select 
                city, 
                state, 
                max(date) as date
            from 
                data
            group by 
                city, 
                state
        ) t2;
    
    0 讨论(0)
提交回复
热议问题