【问题标题】:SQL insert into another table migration with group by having max()SQL 通过 max() 插入到另一个带有组的表迁移中
【发布时间】:2020-10-15 06:17:29
【问题描述】:

我遇到了以下问题。我有两张表,想将一列数据移到另一张表中。

桌子是房子和门。我想将列数据“街道”移动到房子。但是房子有多个门(具有相同的house_id)。所以我需要聚合它们并希望从最新的“created_at”记录中获取“街道”输入。

situation

我的第一次尝试是:

insert into house h ('street') 
    select street 
    from door d 
    where d.house_id = h.id 
    group by house_id 
    having max(created_at)

【问题讨论】:

  • 请用您使用的数据库标记您的问题:mysql、oracle、sql-server...?

标签: sql group-by migration mariadb max


【解决方案1】:

我怀疑您实际上想要一个 update 查询,以在 house 中的现有行上设置 street 的值。

一个选项是带有行限制子句的相关子查询:

update house 
set street = (
    select d.street
    from door d
    where d.house_id = house.id
    order by created_at desc
    limit 1
)

limit 语法因数据库而异 - 但(几乎)都有相同的功能。

【讨论】:

  • 是的,你是对的。 “插入”只是用于新记录,但我想更新房屋数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2010-10-09
  • 2021-11-15
  • 1970-01-01
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多