如何在 mysql 查询中结合聚合与非聚合

How to combine aggregate with nonaggregated in mysql query

我有两个表 Locations 和 competitors,我想根据 mysql 中的时间戳从每个竞争对手订单的位置获取最新行。我不知道如何在不改变 sql 模式的情况下将聚合与非聚合结合起来 'ONLY_FULL_GROUP_BY'

标签看起来像

 Location
| lng       | lat     | competitor_id | timestamp |
| 99.99999  | 88.99999|     1666      |2021-07-29 10:40
| 65.99999  | 36.99999|     1555      |2021-07-29 10:12
| 35.99999  | 42.99999|     1888      |2021-07-29 10:28
| 28.99999  | 58.99999|     1666      |2021-07-29 10:17
| 47.99999  | 32.99999|     1555      |2021-07-29 10:42
| 22.99999  | 15.99999|     1888      |2021-07-29 10:05
 
Competitors
| Name          | team    | competitor_id
| Artial Dedino | Scuderia |     1666      
| Naruto Belica | Redb|          1555      
| Maranelino Kita | Sport|       1888

我试试

SELECT c.`name`,l.lat,l.lng,l.timestamp
FROM competitors as c
INNER JOIN locations as l ON l.competitor_id = c.number
GROUP BY c.number
ORDER BY  l.timestamp DESC

需要这样的结果

 | Naruto Belica | Redb| 2021-07-29 10:42    
 | Artial Dedino | Scuderia | 2021-07-29 10:40  
 | Maranelino Kita | Sport| 2021-07-29 10:28

当 MySQL only_full_group_by 模式打开时,这意味着如果您按某些列进行 GROUP BY,那么您只能 select 两件事之一,您的列分组依据和聚合函数,如 MAX()、MIN()...; 如果您不想更改 sql_mode(这可能会导致将来出现问题), 以下查询应该适合您。

    SELECT max(name) as name,
           max(team) as team,
           max(timestamp)  as timestamp
FROM competitors join location using(competitor_id)
where competitor_id in ( 
select distinct competitor_id from  competitors ) 
group by competitor_id
order by timestamp DESC ;

http://www.sqlfiddle.com/#!9/2cc8a6/1

参考link:

Need result like

| Naruto Belica | Redb| 2021-07-29 10:42    
| Artial Dedino | Scuderia | 2021-07-29 10:40  
| Maranelino Kita | Sport| 2021-07-29 10:28
SELECT c.name, c.team, MAX(l.`timestamp`) timestamp
FROM Competitors c
JOIN Location l USING (competitor_id)
GROUP BY c.name, c.team;

您可以尝试以下方法。

select c.name, l.lat, l.lng, l.timestamp
from competitors c
join (
    select l.* from locations where timestamp = (
        select l2.timestamp from locations where l2.competitor_id = l.competitor_id
        order by l2.timestamp desc
        limit 1
    )
) l on c.competitor_id = l.competitor_id