简体   繁体   English

如何使用SQl语法从MySQL表中的组中选择最新记录

[英]How to select the lastest record from a group in MySQL table using SQl syntax

I'm trying to get the latest row of each group. 我正在尝试获取每个组的最新行。

$SQL = "SELECT location_name, status, timecode FROM status_table WHERE location_name in ('G_01', 'J_01', 'M_01', 'A_01', 'U_01', 'W_01', 'W_1_01', 'C_01', 'G_2_01', 'M_01') GROUP BY location_name ORDER BY status";

The query only pull up the first row, and order by timecode does not work 该查询仅拉起第一行,并且按时间码排序不起作用

It will only pull the first row because the group by is only on one column. 因为group by仅在一个列上,所以它只会拉第一行。

Try including your other selected fields in the GROUP BY clause 尝试将其他选定字段包括在GROUP BY子句中

$SQL = "SELECT location_name, status, timecode FROM status_table 
WHERE location_name in  
('G_01', 'J_01', 'M_01', 'A_01', 'U_01', 'W_01', 'W_1_01', 'C_01', 'G_2_01', 'M_01') 
GROUP BY location_name, status, timecode 
ORDER BY status";

If you have an auto incrementing id column: 如果您具有自动递增的id列:

SELECT location_name, status, timecode FROM status_table WHERE id IN(
   SELECT MAX(id) FROM status_table WHERE location_name in ('G_01', 'J_01', 'M_01', 'A_01', 'U_01', 'W_01', 'W_1_01', 'C_01', 'G_2_01', 'M_01') GROUP BY location_name
) ORDER BY status

Should work by getting the MAX id for each "group" (location name) then get the details for that id, and finally order the resultset by status 应该通过获取每个“组”(位置名称)的最大ID来工作,然后获取该ID的详细信息,最后按状态对结果集进行排序

I cant get you properly but till i understand i think below links really help you 我无法正确帮助您,但直到我了解我认为以下链接确实对您有帮助

1) php/MySQL insert row then get 'id' 1) php / MySQL插入行,然后获取“ id”
2) Get the id of current mysql insert 2) 获取当前mysql插入的id
3) MySQL - Select the last inserted row easiest way 3) MySQL-选择最后插入的行是最简单的方法
4) mysql_insert_id 4) mysql_insert_id

i hope above links are helpful.... 我希望以上链接对您有所帮助。

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

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