我如何为每个grp_id 2行拥有: 当前unix时间戳行之前和之后,
+---------+--------------------+------------+-------+ | id | grp_id | utimes | value | +---------+--------------------+------------+-------+ | 4156187 | 5282 | 1455663600 | 15897 | | 4159888 | 5282 | 1455630000 | 26998 |* | 4156190 | 5282 | 1455676200 | 28497 | | 4156186 | 5282 | 1455661800 | 14097 | | 4156183 | 5282 | 1455652800 | 5097 | | 4156184 | 5282 | 1455656400 | 8697 | | 4156185 | 5282 | 1455660000 | 12297 | | 4156182 | 5282 | 1455651000 | 3297 |* | 4163311 | 7216 | 1455693000 | 45297 | | 4163275 | 7203 | 1455681600 | 33897 | | 4163309 | 7214 | 1455697800 | 50097 | | 4163308 | 7214 | 1455696000 | 48297 | | 4163307 | 7214 | 1455694200 | 46497 | | 4163306 | 7214 | 1455692400 | 44697 | | 4163305 | 7214 | 1455690600 | 42897 | | 4163304 | 7214 | 1455688800 | 41097 | | 4151121 | 4356 | 1455703200 | 55497 | | 4163271 | 7205 | 1455685500 | 37797 | | 4163272 | 7205 | 1455687000 | 39297 | | 4163269 | 7205 | 1455684900 | 37197 | | 4163273 | 7205 | 1455687300 | 39597 | | 4163264 | 7206 | 1455674400 | 26697 | | 4163270 | 7205 | 1455685200 | 37497 | +---------+--------------------+------------+-------+
Example: unix-timestamp : 1455647703
+---------+--------------------+------------+-------+ | id | grp_id | utimes | value | +---------+--------------------+------------+-------+ | 4159888 | 5282 | 1455630000 | 26998 | | 4156190 | 5282 | 1455651000 | 28497 | | 4159889 | XYZ | 1455630000 | 26998 | | 4156191 | XYZ | 1455651000 | 28497 | | 4159883 | ABC | 1455630000 | 26998 | | 4156195 | ABC | 1455651000 | 28497 | +---------+--------------------+------------+-------+
谢谢!
答案 0 :(得分:0)
您可以使用LEFT JOIN
操作执行此操作。 ON
子句包含'业务逻辑':
SELECT t1.*
FROM mytable AS t1
LEFT JOIN mytable AS t2
ON t1.grp_id = t2.grp_id
AND
((t1.utimes < 1455647703 AND t2.utimes < 1455647703 AND t2.utimes > t1.utimes)
OR
(t1.utimes > 1455647703 AND t2.utimes > 1455647703 AND t2.utimes < t1.utimes))
WHERE t1.grp_id = 5282 AND t2.id IS NULL