SQL通过max()插入到另一个具有组的表迁移中
我有以下问题。我有两个表,希望将一列数据移动到另一个表 桌子是房子和门。我想将列数据“street”移动到house。但是房子有多扇门(具有相同的房屋id)。因此,我需要对它们进行聚合,并希望从最新的“created_at”记录中获取“street”输入 我的第一次尝试是:SQL通过max()插入到另一个具有组的表迁移中,sql,group-by,migration,mariadb,max,Sql,Group By,Migration,Mariadb,Max,我有以下问题。我有两个表,希望将一列数据移动到另一个表 桌子是房子和门。我想将列数据“street”移动到house。但是房子有多扇门(具有相同的房屋id)。因此,我需要对它们进行聚合,并希望从最新的“created_at”记录中获取“street”输入 我的第一次尝试是: insert into house h ('street') select street from door d where d.house_id = h.id group by h
insert into house h ('street')
select street
from door d
where d.house_id = h.id
group by house_id
having max(created_at)
我怀疑您实际上需要一个
更新
查询,以便在房屋
中的现有行上设置街道
的值
一个选项是带有row limitig子句的相关子查询:
update house
set street = (
select d.street
from door d
where d.house_id = house.id
order by created_at desc
limit 1
)
limit
语法因数据库而异,但(几乎)所有数据库都具有相同的功能。请用您使用的数据库标记您的问题:mysql、oracle、sql server…?是的,您是对的。“插入”仅用于新记录,但我想更新房屋数据。