我遇到以下SQL查询和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
表格如下所示
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
我希望我的查询返回
3 | 135.6 | CB59
5 | 135.5 | CB46
修改
标签是狗/猫,而cpids是保持狗/猫的临时家庭。
狗/猫从一个家庭搬到另一个家庭。
我需要找到位于:userinput系列中的狗/猫,但前提是他们不在另一个家庭中
我无法改变数据库,只需按原样处理数据,而我不是编写应用程序/数据库模式的人。
答案 0 :(得分:6)
尝试使用LEFT JOIN
SELECT a.id, a.cpid, a.label, a.cpdatetime
FROM mytable AS a
LEFT JOIN mytable AS b ON a.label = b.label AND a.cpdatetime > b.cpdatetime
WHERE a.label LIKE 'CB%' AND a.cpid LIKE :cpid
AND b.label IS NULL
GROUP BY a.label
ORDER BY a.cpdatetime ASC
如果联接条件失败,则第二个表别名b
的字段将设置为NULL
。
或者,使用非相关子查询:
SELECT a.id, a.cpid, a.label, a.cpdatetime
FROM mytable AS a
INNER JOIN (
SELECT label, MIN(cpdatetime) AS cpdatetime
FROM mytable
WHERE label LIKE 'CB%'
GROUP BY label
) AS b ON a.label = b.label AND a.cpdatetime = b.cpdatetime
WHERE a.cpid LIKE '135%'
ORDER BY a.cpdatetime
首先,您会找到每个标签的最小cpdatetime
,然后将其与添加了cpid
条件的第一个表连接起来。
答案 1 :(得分:1)
我认为这就是你想要做的 - 选择每个标签最早ID的ID,然后选择带有135 cpid和CB标签的记录。
SELECT
A.id, cpid, A.label, cpdatetime
FROM
mytable AS a inner join
(select id, label from mytable
group by label
having min(cpdatetime)) as b
on A.label=B.label and A.id=B.id
WHERE
A.label LIKE 'CB%'
AND
cpid LIKE '135%'
GROUP BY A.label
ORDER BY cpdatetime ASC;