简体   繁体   English

获取行之间具有固定值差异的行并减少连续日期

[英]get rows with fixed difference of values between rows and decreasing consecutive date

Structure of my table : ID(int) | NUMBER(int) | CREATED_AT(date) 我的表的结构: ID(int) | NUMBER(int) | CREATED_AT(date) ID(int) | NUMBER(int) | CREATED_AT(date)

If I have three numbers : 10 , 11 and 9 , Can I get all rows from my table with same ratio of NUMBER values with decreasing consecutive CREATED_AT dates? 如果我有三个数字: 10119 ,我可以从我用同样的比例表中的所有行NUMBER的值随连续CREATED_AT日期?

Examples : 例子 :

If my numbers are : 10,11,9 ... The rows may be : 如果我的数字是:10,11,9 ......行可能是:

NUMBER | CREATED_AT
50     | 2012-03-18
51     | 2012-03-17
49     | 2012-03-16

Result must be "50" 结果必须是“50”

If my numbers are : 50,40,60 ... The rows may be : 如果我的数字是:50,40,60 ......行可能是:

NUMBER | CREATED_AT
100    | 2012-02-20
90     | 2012-02-19
110    | 2012-02-18

Result must be "100" 结果必须是“100”

... ...

I wasted a half of day for this, but I still have no Idea where to start... 我浪费了半天的时间,但我仍然不知道从哪里开始......

PS : I have about 5 000 rows in my table. PS:我桌上有大约5000行。

UPDATE UPDATE

I did it with a bit of php code and a lot of mysql queries. 我用一些PHP代码和很多mysql查询做到了。 Script execution time : ~6 seconds. 脚本执行时间:~6秒。 [Tested on godaddy deluxe hosting] =) [测试godaddy豪华主机] =)

I haven't tested it myself, but you can try this: 我自己没有测试过,但你可以尝试这个:

SELECT a.*,b.*,c.*
FROM table_name a
INNER JOIN table_name b 
ON b.NUMBER = a.NUMBER + $range1 and DATEDIFF(b.CREATED_AT, a.CREATED_AT) = 1
INNER JOIN table_name c 
ON c.NUMBER = b.NUMBER + $range2 and DATEDIFF(c.CREATED_AT, b.CREATED_AT) = 1

$range1 , $range2 are variables number1 - number2 and number2 - number3. $range1$range2是变量number1 - number2和number2 - number3。

In your example you have 10, 11 and 9. So, if t1.number = 10, then t2.number = t1.number + 1 and t3.number = t2.number - 2. This can be written into a query in this form - 在你的例子中你有10,11和9.所以,如果t1.number = 10,那么t2.number = t1.number + 1和t3.number = t2.number - 2.这可以写入一个查询表格 -

SELECT t1.NUMBER
FROM (SELECT 50 AS `first`, 40 AS `second`, 60 AS `third`) AS  seq
INNER JOIN `table` t1
    ON `seq`.`first` <> t1.NUMBER
INNER JOIN `table` t2
    ON `seq`.`second` <> t2.NUMBER
    AND t1.CREATED_AT - INTERVAL 1 DAY = t2.CREATED_AT
    AND CAST(t1.NUMBER AS SIGNED) - CAST(t2.NUMBER AS SIGNED) = `seq`.`first` - `seq`.`second`
INNER JOIN `table` t3
    ON `seq`.`third` <> t3.NUMBER
    AND t2.CREATED_AT - INTERVAL 1 DAY = t3.CREATED_AT
    AND CAST(t2.NUMBER AS SIGNED) - CAST(t3.NUMBER AS SIGNED) = `seq`.`second` - `seq`.`third`;

EDIT - added the CAST to deal with negatives 编辑 - 添加了CAST来处理否定

This is not very efficient due to the join criteria but given such a small dataset it should be fine. 由于连接标准,这不是非常有效,但是如果给出这么小的数据集,它应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM