mongoose00318 Posted August 25, 2020 Share Posted August 25, 2020 I'm trying to select all of the most recent records for each 'order_id' with the following table structure: So with that example above I would want record 6840 because it is the newest record for order 5157. SELECT pda.* FROM production_data_archive pda INNER JOIN ( SELECT MAX(insert_time) as MAX_insert_time FROM production_status_archive pda2 GROUP BY order_id ) ON pda.order_id = pda2.order_id I'm not sure what I'm doing wrong with my query but I'm getting an error. Quote Link to comment https://forums.phpfreaks.com/topic/311384-select-maxdate-from-a-group-of-records/ Share on other sites More sharing options...
Barand Posted August 25, 2020 Share Posted August 25, 2020 You need to match aginst the subquery on id and time. Table subqueries require an alias (as virtual table name) try SELECT pda.* FROM production_data_archive pda INNER JOIN ( SELECT order_id MAX(insert_time) as insert_time FROM production_status_archive GROUP BY order_id ) pda2 USING (order_id, inser_time) Quote Link to comment https://forums.phpfreaks.com/topic/311384-select-maxdate-from-a-group-of-records/#findComment-1580957 Share on other sites More sharing options...
mongoose00318 Posted August 25, 2020 Author Share Posted August 25, 2020 I tried this and I think it gave me what I wanted? SELECT *, MAX(insert_time) FROM production_data_archive GROUP BY order_id Quote Link to comment https://forums.phpfreaks.com/topic/311384-select-maxdate-from-a-group-of-records/#findComment-1580958 Share on other sites More sharing options...
mongoose00318 Posted August 25, 2020 Author Share Posted August 25, 2020 Maybe I didn't need the join? Quote Link to comment https://forums.phpfreaks.com/topic/311384-select-maxdate-from-a-group-of-records/#findComment-1580959 Share on other sites More sharing options...
Barand Posted August 25, 2020 Share Posted August 25, 2020 3 hours ago, mongoose00318 said: I tried this and I think it gave me what I wanted? If it did it was only by luck. The information returned for each id could come from any of the records with that id, not necessarily the one with the max value. Quote Link to comment https://forums.phpfreaks.com/topic/311384-select-maxdate-from-a-group-of-records/#findComment-1580963 Share on other sites More sharing options...
mongoose00318 Posted August 26, 2020 Author Share Posted August 26, 2020 @Barand Hmm...okay thanks for the heads up. I'll keep that in mind next time I have to do something similar. Quote Link to comment https://forums.phpfreaks.com/topic/311384-select-maxdate-from-a-group-of-records/#findComment-1580977 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.