简体   繁体   English

使用来自另一个表的计数更新Oracle中的特定行

[英]Update specific rows in Oracle using the count from another table

I am trying to update some records in one table (street) with a count from another table (house). 我试图用另一个表(房屋)的计数来更新一个表(街道)中的一些记录。 I am trying to update the house_count in the street table with the correct number of houses on that street. 我正在尝试使用该街道上的正确房屋数量来更新街道表中的house_count。 I only want to update the records that are incorrect. 我只想更新不正确的记录。 I have been able to do this is MSSQL using the code below: 我已经能够使用下面的代码来执行此操作:MSSQL:

CREATE TABLE street
(
name varchar(255),
house_count int
);

Create table house
(
id varchar(255),
street_name varchar(255)
);

insert into street values ('oak',1)
insert into street values ('maple',2)
insert into street values ('birch',4)
insert into street values ('walnut',1)

insert into house values (1,'oak')   
insert into house values (2,'oak')
insert into house values (1,'maple')
insert into house values (2,'maple')
insert into house values (1,'birch')
insert into house values (2,'birch')
insert into house values (3,'birch')
insert into house values (1,'walnut')

update s set s.house_count= hc.ActualCount
from street s
inner join
(select s.name, count(s.name) as 'ActualCount', s.house_count
from street s
inner join house h on s.name=h.street_name
group by s.name, s.house_count
having count(s.name) <> s.house_count) hc ON s.name=hc.name
where s.name=hc.name

I have a need to do something similar in Oracle but have ran into issues. 我需要在Oracle中做类似的事情,但是遇到了问题。 From what I have found the join is not possible in Oracle but I am having a hard time getting something that will work. 从我发现的结果来看,无法在Oracle中加入该连接,但是我很难获得可以使用的连接。 Any help in getting something like this to work in Oracle is greatly appreciated. 非常感谢在Oracle中使类似的东西起作用的任何帮助。

Thanks 谢谢

You can do this with a correlated subquery: 您可以使用相关子查询来执行此操作:

update street
    set house_count = (select count(s.name)
                       from house h
                       where street.name = h.street_name
                      );

This is a little different from your approach, because it will update all streets, even when the count does not change. 这与您的方法稍有不同,因为即使计数不变,它也会更新所有街道。 There is no performance advantage using a subquery in trying to prevent the update. 在尝试阻止更新时,使用子查询没有性能优势。

EDIT: 编辑:

This should solve the problem with the apartment streets versus house streets: 这应该可以解决公寓街道与房屋街道的问题:

update street
    set house_count = (select count(s.name)
                       from house h
                       where street.name = h.street_name
                      )
    where exists (select 1 from house h where street.name = h.street_name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM