MySQL implementation of the Users table and Logoin_log table is a one-to-many, now is to find the user's information to correlate some of the Logoin_log table data, because a table is more than one side, to more his data to do some matching conditions, The purpose of this SQL is to isolate the latest log records for each user.
Some people suggest a table connection to filter, but that is very troublesome, Xiao Tao I flatly refused, and then I adopted another ingenious method:
List of the time to use the first check a table, here is the Users table, and then pass the value to the method, the method to encapsulate the query Logoin_log, at this time to pass the ID in reverse order, return the corresponding value, so you can get the latest log records, so it is more simple, proud ... The friends who firmly use the table to connect, try this method quickly.
The Users table and the Auth_token_log table are One-to-many, and now it's time to find the user's information to correlate some of the Auth_token_log tables, because table A is more than one side,
He's going to need more data to match some conditions.
The purpose of this SQL is to isolate the latest log records for each user.
Original wording
The code is as follows |
Copy Code |
SELECT Users.first_name, Users.email_address, USERS.TP_USER_ID, Users.tp_username, Auth_token_log.module_access, Auth_token_log.created_date From Users INNER JOIN auth_token_log on users.id = auth_token_log.user_id WHERE Auth_token_log.id in ( SELECT Max (ID) From Auth_token_log WHERE auth_token_log.user_id = Users.id )
|
Own understanding
code is as follows |
copy code |
SELECT users.first_name, users.email_address, users.tp_user_id, users.tp_username, auth_token_log.module_access, auth_token_log.created_date from users INNER JOIN auth_token_log on users.id = auth_token_log.user_id WHERE auth_token_log.id in ( select max (auth_token_log.id) from auth_token_log, users WHERE auth_token_log.user_id = users.id GROUP by users.id ) |
The understanding of the original wording is
First Find out
The code is as follows |
Copy Code |
SELECT X From Users INNER JOIN auth_token_log on users.id = auth_token_log.user_id
|
Records, and then for each row of X, take out this line of X to join with a new Auth_token_log table, and then filter out log.user_id = x. User.ID all records, and then find Max (ID), which is the ID of the latest log record