根据条件从表中获取 id

Get the id from the table based on the condition

提问人:user22760244 提问时间:11/7/2023 最后编辑:user22760244 更新时间:11/7/2023 访问量:49

问:

我有 2 个表 t1 和 t2,两个表都有 3 列 id、status、run_date。

从 t1 中找到 id

  1. 在 T2 中与在 T1 中具有不同的状态,并且 T2 中的run_date比 T1 早

  2. 在 T2 中不存在

3)在 t2 表中,同一 id 可能多次出现,运行日期不同 为了进行比较run_date请仅取最近发生的事件。

我尝试了以下查询,但我在第二个条件(状态差异)作为子查询返回多行时出现错误。请帮助解决这个问题。

错误: [UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY.MUST_AGGREGATE_CORRELATED_SCALAR_SUBQUERY] 不支持的子查询表达式:必须聚合相关的标量子查询,最多返回一行。第 11 行 POS 31;

WITH most_recent_id AS(
    select id,max(run_date) as latest_run_date
    from t2
    group by id
)

SELECT t1.id
FROM t1
LEFT JOIN most_recent_id ON t1.id = most_recent_id.id
WHERE (most_recent_id.id IS NULL) OR 
(t1.status <> (select status from t2 a where a.id=t1.id and   a.run_date=most_recent_id.latest_run_date)
AND most_recent_id.latest_run_date < t1.run_date)
SQL MySQL 数据库 子查询 common-table-expression

评论

0赞 Ivan Yuzafatau 11/7/2023
请尝试而不是在子查询中。select TOP 1 statusselect status

答:

-1赞 Rob Eyre 11/7/2023 #1

您可以从不匹配的 LEFT JOIN 开始,以获取 t2 中每个 id 的最新行数:

SELECT t2.id, t2.status, t2.run_date
FROM t2
LEFT JOIN t2 t2later ON
  t2.id = t2later.id
  AND t2.run_date < t2later.run_date
WHERE t2later.run_date IS NULL

然后,您可以将其用作第二个不匹配的 LEFT JOIN 中的子查询,以获取与条件相反的 t1 行:

SELECT t1.id
FROM t1
LEFT JOIN (
    SELECT t2.id, t2.status, t2.run_date
    FROM t2
    LEFT JOIN t2 t2later ON
      t2.id = t2later.id
      AND t2.run_date < t2later.run_date
    WHERE t2later.run_date IS NULL
    ) t2max ON
    t1.id = t2max.id
    AND (t1.status = t2max.status OR t1.run_date < t2max.run_date)
WHERE t2max.id IS NULL