我遇到以下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
Run Code Online (Sandbox Code Playgroud)
表格看起来像这样
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
Run Code Online (Sandbox Code Playgroud)
我希望我的查询返回
3 | 135.6 | CB59
5 | 135.5 | CB46
Run Code Online (Sandbox Code Playgroud)
编辑
标签是狗/猫,而cpids是保持狗/猫的临时家庭.
狗/猫从家庭移动到家庭.
我需要找到位于:userinput系列中的狗/猫,但前提是他们不在另一个家庭中
我无法改变数据库,只需按原样处理数据,而我不是编写应用程序/数据库模式的人.
尝试使用以下方法避免相关的子查询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
Run Code Online (Sandbox Code Playgroud)
如果连接条件失败,则第二个表别名的字段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
Run Code Online (Sandbox Code Playgroud)
首先,您找到cpdatetime每个标签的最小值,然后将其与添加附加cpid条件的第一个表连接.
| 归档时间: |
|
| 查看次数: |
17211 次 |
| 最近记录: |