I'm having problem with the following SQL query and MySQL
SELECT
id, cpid, label, cpdatetime
FROM
mytable AS a
WHERE
id NOT IN
(
SELECT
id
FROM
mytable AS b
WHERE
a.label = b.label
AND
a.cpdatetime > b.cpdatetime
)
AND
label LIKE 'CB%'
AND
cpid LIKE :cpid
GROUP BY label
ORDER BY cpdatetime ASC
the table looks like this
1 | 170.1 | CB55 | 2013-01-01 00:00:01
2 | 135.5 | CB55 | 2013-01-01 00:00:02
3 | 135.6 | CB59 | 2013-01-01 00:00:03
4 | 135.5 | CM43 | 2013-01-01 00:00:04
5 | 135.5 | CB46 | 2013-01-01 00:00:05
6 | 135.7 | CB46 | 2013-01-01 00:00:06
7 | 170.2 | CB46 | 2013-01-01 00:00:07
I would like my query to return
3 | 135.6 | CB59
5 | 135.5 | CB46
Edit
labels are dogs/cats and cpids are temporary family keeping the dogs/cats.
Dogs/cats move from family to family.
I need to find dogs/cats who were in :userinput family but only if they were not in another family previously
I can't alter the database and just have to work with the data as they are and I'm not the one who wrote the application/database schema.
:cpid = '13%'perhaps?cpid != '135%' AND a.cpdatetime > b.cpdatetime