I've been trying to LEFT JOIN a table to itself depending on the TIMESTAMP (nearest before this row) and another column STABILISATION (with value 1)
query for the test table:
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`UID` varchar(40) NOT NULL,
`CREATED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`STABILISATION` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`UID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
TRUNCATE `test`;
INSERT INTO `test` (`UID`, `CREATED`, `STABILISATION`) VALUES
('1', '2014-03-12 09:22:41', 1),
('2', '2014-03-12 09:24:20', 0),
('3', '2014-03-12 09:24:35', 0),
('4', '2014-03-12 09:24:39', 1),
('5', '2014-03-12 09:24:41', 0),
('6', '2014-03-12 10:02:17', 1),
('7', '2014-03-12 10:02:24', 0),
('8', '2014-03-12 11:00:15', 0),
('9', '2014-03-12 11:01:08', 1),
('10', '2014-03-12 11:01:17', 0);
I'm trying to get t2_UID COLUMN just like this
ID CREATED STABILISATION t2_UID '1', '2014-03-12 09:22:41', 1, 1 '2', '2014-03-12 09:24:20', 0, 1 '3', '2014-03-12 09:24:35', 0, 1 '4', '2014-03-12 09:24:39', 1, 4 '5', '2014-03-12 09:24:41', 0, 4 '6', '2014-03-12 10:02:17', 1, 6 '7', '2014-03-12 10:02:24', 0, 6 '8', '2014-03-12 11:00:15', 0, 6 '9', '2014-03-12 11:01:08', 1, 9 '10', '2014-03-12 11:01:17', 0, 9
whenever the STABILISATION changes the t2_UID should change also!
The closest I get is with this query:
SELECT t1.*, t2.UID AS t2_UID FROM test AS t1 LEFT JOIN test as t2 ON t2.UID = (SELECT UID FROM test as t3 WHERE t3.STABILISATION = 1 ORDER BY ABS(TIMEDIFF(t1.CREATED, t3.CREATED)) LIMIT 1)
the closest