gpt4 book ai didi

mysql - SQL SELECT WHERE NOT IN 来自同一表查询

转载 作者:IT王子 更新时间:2023-10-28 23:44:12 27 4
gpt4 key购买 nike

我在使用以下 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

编辑

标签是狗/猫,cpid 是临时饲养狗/猫的家庭。

狗/猫从一个家庭搬到另一个家庭。

我需要找到属于 :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

Fiddle

如果连接条件失败,第二个表别名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 条件的第一个表连接起来。

关于mysql - SQL SELECT WHERE NOT IN 来自同一表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15018026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com