MySQL:基于两列内连接进行更新

标签 mysql

我有table_aa_audittable_a 具有列 idclient_idoriginating_client_ida_audit 具有相同的列;它用于跟踪 table_a 的更改。

我有这个选择查询来获取table_a中的所有行,其中client_id为NULL,originating_client_id为NULL,并且审计表中有一行包含client_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? */

select query

我想要做的是:对于table_a中的每一行,其中client_id IS NULLoriginating_client_id IS NULL,找到第一行具有相同 id 且具有 client_ida_audit,然后设置 table_a.originating_client_id = client_id 来自 a_audit

的该行

intent

最佳答案

获取 a_audit 中每个 id 具有最小 updated_onclient_id 而非 的所有行null 并连接到 table_a:

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

关于MySQL:基于两列内连接进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662312/

相关文章:

php - SQL : Get all rows if date is nul

mysql - 关于 SQL 中时间戳的思考,比较当前年份

MySQL if 条件则左连接

mysql - Wordpress 距离搜索 SQL

带有 Ajax 的 PHP 数组 - 获取数据的正确方法?

mysql - 总和列查询中多一行

MySQL 即使在提交后也没有显示更新的数据

php - MySQL更新问题

mysql - 在 Centos 上安装 MySQL Workbench 时出现问题

PHP议程与mysql回显表中的记录