I have the following structure:
CREATE TABLE IF NOT EXISTS `myTable` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`time` int(11) NOT NULL,
`item` varchar(255) NOT NULL,
`price` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `time` (`time`),
KEY `item` (`item`),
KEY `price` (`price`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
INSERT INTO `myTable` (`ID`, `time`, `item`, `price`) VALUES
(1, 100, 'cat', 10),
(2, 101, 'cat', 10),
(3, 102, 'cat', 9),
(4, 103, 'cat', 11),
(5, 104, 'cat', 10),
(6, 105, 'cat', 10),
(7, 106, 'cat', 11);
I’m trying to figure out a query that would return the following:
time item price
---- ---- -----
100 cat 10
102 cat 9
103 cat 11
104 cat 10
106 cat 11
It’s ordered by time, and shows only rows where the price is different to the price before it (Edit: *According to time*).
EDIT:
Maybe I made the original problem too simple, what if it was more complex with data like this:
INSERT INTO `myTable` (`ID`, `time`, `item`, `price`) VALUES
(1111, 100, 'cat', 10),
(21, 105, 'cat', 10),
(31, 108, 'cat', 9),
(411, 109, 'cat', 11),
(512, 110, 'cat', 10),
(61, 114, 'cat', 10),
(72, 120, 'cat', 11),
(8, 100, 'dog', 20),
(93, 102, 'dog', 20),
(104, 108, 'dog', 29),
(111, 109, 'dog', 31),
(122, 155, 'dog', 20),
(13, 165, 'dog', 20),
(1445, 172, 'dog', 31);
In the above, the ID column is all messed up, perhaps there are other records in between. Also the time no longer increments by 1 and I’ve thrown a dog into the mix.
The query you need is this:
It takes advantage of the fact that time is an alternate key for the table. We take all the rows from
myTable(let’s call it current) such that its price is different than that of the previous row based on the the value of the alternate key time (lets call this set previous).To do this, we need a correlated subquery that identifies the highest value of
timeless than or equal to the value of oftimefor the current row. So…we wind up referencingmyTablethrice:Easy!