简体   繁体   中英

Determine 'valid until' date in MySQL query

In this table I store changeable values for certain spids. As days go by, these values can change, and an spid can get a new value.

Now I want to find out until when a certain value is enabled.

This is the data for a single spids

uid  spid   propertyvalue   creationdate      
--------------------------------------------------
1    3      First name       2010-01-17 22:34:00
37   3      Second name      2010-01-18 01:07:24
38   3      Third name       2010-01-18 01:09:00
39   3      Fourth name      2010-01-18 01:18:16
40   3      Fifth name       2010-01-18 01:20:02

So the first value starts at 2010-01-18 01:07:24 and would be valid until 2010-01-18 01:01:00 .

I already tried this query:

SELECT s1 . * , 
       s2.creationdate AS datetwo
  FROM salespointproperty s1
  JOIN salespointproperty s2 ON s1.spid = s2.spid
                            AND s1.creationdate < s2.creationdate

That gives me a lot of double-records (some of them wrong), and it always leaves out the last new name (as it doesn't have a new creationdate following it) Example:

uid spid    propertyvalue    creationdate           datetwo
-------------------------------------------------------------- 
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:07:24 *
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:09:00
37  3       Second name      2010-01-18 01:07:24    2010-01-18 01:09:00 *
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:18:16
37  3       Second name      2010-01-18 01:07:24    2010-01-18 01:18:16
38  3       Third name       2010-01-18 01:09:00    2010-01-18 01:18:16 *
1   3       First name       2010-01-17 22:34:00    2010-01-18 01:20:02
37  3       Second name      2010-01-18 01:07:24    2010-01-18 01:20:02
38  3       Third name       2010-01-18 01:09:00    2010-01-18 01:20:02
39  3       Fourth name      2010-01-18 01:18:16    2010-01-18 01:20:02 *

Only the lines with an asterix are correct. The fifth name is missing.

Assuming that in your example, uid 37 is valid until uid 38, uid 38 is valid until uid 39 etc.

SELECT
  s1.uid,
  s1.spid,
  s1.propertyvalue,
  s1.creationdate,
  MIN(s2.creationdate) AS datetwo
FROM salespointproperty s1
INNER JOIN salespointproperty s2
    ON s1.spid = s2.spid
    AND s1.creationdate < s2.creationdate
GROUP BY
  s1.uid,
  s1.spid,
  s1.propertyvalue,
  s1.creationdate;

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