11

我遇到以下 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 家庭的狗/猫,但前提是它们以前不在另一个家庭中

我无法更改数据库,只需要按原样处理数据,而且我不是编写应用程序/数据库模式的人。

4

2 回答 2

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条件的第一个表连接起来。

于 2013-02-22T06:53:05.720 回答
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;

http://sqlfiddle.com/#!2/ccccf/16

于 2013-02-22T06:46:22.763 回答