基本上我想根据另一个表的 id 从一个表中选择数据。所以算法是这样的:
foreach i in (select distinct id from table1)
{
select * from table2 where table2.id=i;
}
如何使用 SQL 查询执行此功能?我知道我们可以使用连接等而不是循环,但是,我的要求是我只需要在 for 循环中一个一个地传递 id。
select * from table2 where table2.id IN (select distinct id from table1)
使用for而不是foreach.
将 PL/SQL 放入一个begin .... end;块中(但见declare下文)
=i应该读=i.id为select 语句中的i完整记录,但您只对它的id字段感兴趣。
在 PL/SQL 中,一条select语句必须获取into一个变量。因此,您必须声明一个相应的变量:r table1%rowtype
此类变量的声明在declare ...PL/SQL 块的部分中。
那么“算法”就变成了
declare
r table2%rowtype;
begin
for i in (select distinct id from table1) loop
select * into r from table2 where table2.id = i.id;
end loop;
end;