简体   繁体   中英

Relating Two Tables Based on Nearby Dates

In my application a user can login and then share something. I'd like to get their latest login information relative to the date that they shared something (eg, the MAX login date that was before than the share date)

I have two tables (they are related by csh.actor = ul.user_id ):

CollectionShares (csh)

| id | actor | shareDate

UsersLogins (ul)

| id | user_id | httpReferer | browser | ipAddress | loginDate

One of my attempts:

SELECT
    csh.shareDate AS shareDate,
    ul.httpReferer AS httpReferer,
    ul.browser AS browser,
    ul.ipAddress AS ipAddress,
    max(ul.loginDate) AS nearestLastLoginDate
FROM collectionsharehistory csh
JOIN userslogins ul ON 
    csh.actor = ul.user_id 
    AND 
    ul.loginDate <= csh.shareDate
GROUP BY csh.id;

This actually seems to be getting the right ul.loginDate , but the other ul columns are incorrect and do not seem to actually match up with the returned loginDate .

You can use the following query:

SELECT ul.id, ul.user_id, ul.ipAddress, ul.loginDate, csh.shareDate                  
FROM UsersLogins AS ul
INNER JOIN CollectionSharesHistory AS csh 
  ON ul.user_id = csh.actor AND ul.loginDate <= shareDate

in order to get all user logins having a related post-dated CollectionSharesHistory record.

Using variables you can select the required records out of the derived table produced by the above query:

SELECT id, user_id, ipAddress, loginDate, shareDate
FROM (
  SELECT id, user_id, ipAddress, loginDate, shareDate,
         @rn := IF (@user <> user_id,
                   IF (@user := user_id, 1, 1),
                   IF (@user := user_id, @rn + 1, @rn + 1)) AS rn
  FROM ( ... above query here ... ) AS t
  CROSS JOIN (SELECT @user := -1, @rn := -1) AS vars
  ORDER BY user_id, loginDate DESC, shareDate ASC ) AS s
WHERE s.rn = 1

@rn variable is used to enumerate records within each user_id partition. Once user_id changes @rn is reset and enumeration starts again at 1.

The ORDER BY clause places the required record at the top of each user_id slice. Hence, we can easily select the required row using an outer query with a WHERE s.rn = 1 clause.

Demo here

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