I am currently developing a website for a friend and I ran into an issue that I am not able to solve to my satisfaction.
I was asked to log the user logins, and my approach was, to create a table that holds the columns:
Now if the table lookes something like this:
id -- user_id -- login_time --------------- login_ip
1 ----- 1 --------- 2016-05-29 17:21:47 --- 11.0.0.1
2 ----- 1 --------- 2016-05-29 17:22:12 --- 11.0.0.1
3 ----- 2 --------- 2016-05-29 17:23:49 --- 11.0.0.1
4 ----- 3 --------- 2016-05-29 17:25:57 --- 11.0.0.1
5 ----- 2 --------- 2016-05-29 17:28:34 --- 11.0.0.1
6 ----- 1 --------- 2016-05-29 17:30:35 --- 11.0.0.1
7 ----- 3 --------- 2016-05-29 17:31:28 --- 11.0.0.1
8 ----- 3 --------- 2016-05-29 17:31:58 --- 11.0.0.1
9 ----- 2 --------- 2016-05-29 17:44:29 --- 11.0.0.1
How do I get the data from row 6 most efficiently? As this is the last time the user with "the user_id" of 1 logged in, is there a way to "ask" mysql to get the latest entry that has the "user_id = 1"?
My current approach would be
("SELECT * FROM login_tracking WHERE user_id = 1 ORDER BY id DESC LIMIT 1")
That is not a problem if tha database is small, but if it grows larger, it will be inefficient in my eyes.
Or would it be a better option to add the "login_time" and the "login_ip" to the users table and get the information from there, when the user last logged in and keep the same + the past login entries in the "login_tracking" table?
You´re original select is the best option:
select * from login_tracking where user_id = 1 order by id desc limit 1
But, be aware to create an index on both columns id and user_id:
create index two_cokumn_index on login_tracking (id , user_id );
This will really increase query performance.
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.