简体   繁体   中英

How do I get the last and second last inserted data of a certain user in table in mysql?

create table table_1(user_id int, bmi int, date date)

Insert into table_1(user_id, bmi ,date) values (1, '20', '2020-05-01'),
                                       (1, '25', '2020-05-10'),
                                       (1, '30', '2020-05-20');

Here I want to retrieve the two latest inserted 'bmi' of user '1' so that I can compare his improvements,etc. The result should give me the 'bmi' of dates 2020-05-10 and 2020-05-20

Solution (only works in MYSQL 8.0):

SELECT bmi FROM 
(
SELECT *
,ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY date DESC) row_num
FROM input_table
)
WHERE user_id = 1 AND row_num <= 2;

Solution 2 works in any MySQL version:

SELECT bmi
FROM input_table
WHERE user_id = 1
ORDER BY date DESC LIMIT 2;

Got the answer: SELECT bmi FROM table_1 WHERE user_id=1 ORDER BY date DESC LIMIT 2; credits: @Luuk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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