简体   繁体   中英

how to to get a record from mysql 20 consecutive days?

I have a table XX. i need to get the records which are 20 days consecutive gap .below is my table look

 ID    ISmen    Date
  1      0      2013-05-2 
  2      0      2013-05-2 
  3      0      2014-04-2 
  4      1      2014-05-2 
  5      1      2014-05-2 
  6      0      2014-05-2 
  7      0      2014-05-2 
  8      0      2014-05-2 
  9      1      2014-05-25 
  10     1      2014-05-25 
  11     0      2014-05-26 
  12     1      2014-05-27
  13     0      2014-05-28 

From the above table i need to get the records which are ismen is 1 and the next record ismen is also 1 (ie 4,5 and 9,10 but not 12).and one more thing 4,5 and 9,10 should have 20 days gap

i am getting the records which are 4,5 and 9,10 ..but i can't able to check date difference between the records .i know we can achieve in the loop but i am trying to get in MySQL is it possible or not.I try below query.thanks in advance for help

SELECT *
FROM XX t1,
     XX t2
WHERE (t1.ID=t2.ID+1
       OR t1.ID=t2.ID-1)
  AND t1.Ismen=1
  AND t2.Ismen=1

There is a 23 day gap between |4|5| to |9|10| but ignoring the sample data precision, this result:

| ISMEN | T1ID | T2ID |                     T1DATE |                     T2DATE |
|-------|------|------|----------------------------|----------------------------|
|     1 |    4 |    9 | May, 02 2014 00:00:00+0000 | May, 25 2014 00:00:00+0000 |
|     1 |    5 |    9 | May, 02 2014 00:00:00+0000 | May, 25 2014 00:00:00+0000 |
|     1 |    4 |   10 | May, 02 2014 00:00:00+0000 | May, 25 2014 00:00:00+0000 |
|     1 |    5 |   10 | May, 02 2014 00:00:00+0000 | May, 25 2014 00:00:00+0000 |

was produced by this query:

select
        t1.ismen
      , t1.id     as t1id
      , t2.id     as t2id
      , t1.`date` as t1date
      , t2.`date` as t2date
from table1 as t1
inner join table1 as t2 on t1.ismen = t2.ismen
and t1.`date` + INTERVAL 23 DAY = t2.`date`

The wanted gap between records can be defined in the join conditions (change to 20 or whatever). But do note there is nothing to stop 4 relating to 9 and 10 or 5 to 9 & 10 so you get 4 records in total.

see: http://sqlfiddle.com/#!9/8d941/1

You could reduce that result by some means (eg using row_number() but I don't know if that is required.

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