MySQL:基于两列内部连接进行更新
我有表a和表a审计。表a有列id、客户机id、原始客户机id。a审计有相同的列;它用于跟踪对表a的更改 我使用此select查询获取表a中的所有行,其中客户端id为NULL,原始客户端id为NULL,并且审核表中有一行包含客户端id:MySQL:基于两列内部连接进行更新,mysql,Mysql,我有表a和表a审计。表a有列id、客户机id、原始客户机id。a审计有相同的列;它用于跟踪对表a的更改 我使用此select查询获取表a中的所有行,其中客户端id为NULL,原始客户端id为NULL,并且审核表中有一行包含客户端id: select t.id, t.client_id, t.originating_client_id, a.client_id from table_a t inner join a_audit a on a.id =
select t.id,
t.client_id,
t.originating_client_id,
a.client_id
from table_a t
inner join a_audit a
on a.id = t.id
where t.client_id is null
and t.originating_client_id is null
and a.client_id is not null
group by ur.user_role_id /* not necessary? */
我想做的是:对于表a中的每一行,其中client_id为NULL,origing_client_id为NULL,找到具有相同id和client_id的_审计中的第一行,然后设置表a。origing_client_id=来自该_审计行的client_id
获取每个id和客户端\u id的最小更新\u为非空的\u审核的所有行,并连接到表\u a:
您所说的审计表中的第一行是什么意思?如果将有两行具有相同的id且客户端id不为null,那么会是什么?@lypskee-我想要第一行,因为客户端id可能已更改,但第一行是原始的aka原始客户端id。@lypskee-审核表确实包含时间戳列。为了这篇文章,我们可以将其称为“审核。更新”。请参见第一个选择,为什么不在desc limit 1上按更新的\u进行排序?limit 1只返回一行。我为什么要用它?您需要使用client\u id不为null且每个id的最小更新值为on的\u审核中的所有行。我不完全理解and not exists语句在做什么。那很聪明。谢谢
update table_a t inner join (
select a.* from a_audit a
where a.client_id is not null
and not exists (
select 1 from a_audit
where id = a.id and updated_on < a.updated_on
)
) a on a.id = t.id
set t.originating_client_id = a.client_id
where t.client_id is null and t.originating_client_id is null