简体   繁体   English

Select 都带有 MAX id 在 MySQL

[英]Select all with MAX id in MySQL

I have a table machines and a table machine_logs , every 5 hours new logs are inserted in the logs table, so for example: the machine with ID 7 have a lot of logs but I only need the last one.我有一个表machines和一个表machine_logs ,每 5 小时在日志表中插入新日志,例如:ID 为 7 的机器有很多日志,但我只需要最后一个。

I have this query:我有这个查询:

SELECT MAX(id), machine_id FROM machine_logs GROUP BY machine_id;

But when I want to SELECT more columns, MySQL throws this error:但是当我想要 SELECT 更多列时,MySQL 会抛出这个错误:

SELECT MAX(id), total, machine_id FROM machine_logs GROUP BY machine_id; 

[42000][1055] Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db.machine_logs.total' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

How can I achieve this without changing the sql_mode ?如何在不更改sql_mode的情况下实现这一目标? Is there any other way to get only the most recent ID in every case?有没有其他方法可以在每种情况下只获取最新的 ID? Remember that the query returns a lot of results , not just 1.请记住,查询会返回很多结果,而不仅仅是 1 个。

EDIT: There are around 400 machines, every machine has logs but I only need the most recent one.编辑:大约有 400 台机器,每台机器都有日志,但我只需要最新的一台。 The output will have 400 rows, every most recent log associated to every machine. output 将有 400 行,每个最近的日志都与每台机器相关联。 Every machine has 100+ logs.每台机器都有 100 多条日志。

You can select more data with subquery as follows:您可以使用子查询 select 更多数据,如下所示:


SELECT id, total, machine_id FROM
Machine_logs where id in (select max(id) from machine_logs GROUP BY machine_id); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM