【发布时间】:2009-08-05 19:27:34
【问题描述】:
这是帮助您理解我的问题的代码:
create table con ( content_id number);
create table mat ( material_id number, content_id number, resolution number, file_location varchar2(50), file_size number);
create table con_groups (content_group_id number, content_id number);
insert into con values (99);
insert into mat values (1, 99, 7, 'C:\foo.jpg', 1024);
insert into mat values (2, 99, 2, '\\server\xyz.mov', 350000);
insert into mat values (3, 99, 5, '\\server2\xyz.wav', 175000);
insert into con values (100);
insert into mat values (4, 100, 5, 'C:\bar.png', 2048);
insert into mat values (5, 100, 3, '\\server\xyz.mov', 27400);
insert into mat values (6, 100, 7, '\\server2\xyz.wav', 400);
insert into con_groups values (10, 99);
insert into con_groups values (10, 100);
SELECT m.material_id,
m.content_id,
(SELECT max(file_location) keep (dense_rank first order by resolution desc)
FROM mat
WHERE mat.content_id = m.content_id
/* AND ...
AND ...
AND ... */) special_mat_file_location,
(SELECT max(file_size) keep (dense_rank first order by resolution desc)
FROM mat
WHERE mat.content_id = m.content_id
/* AND ...
AND ...
AND ... */) special_mat_file_size
FROM mat m
WHERE m.material_id IN (select material_id
from mat
inner join con on con.content_id = mat.content_id
inner join con_groups on con_groups.content_id = con.content_id
where con_groups.content_group_id = 10);
我将注释 AND 用于强调这是一个简化的示例;我的真实查询中的子查询更复杂,条件更多。
我的问题是:我想避免在子查询中为两列 (file_location and file_size) 重复所有条件,因为条件完全相同。我很乐意使用公用表表达式(即使用 WITH 子句的子查询分解),但我不能因为子查询中的“WHERE mat.content_id = m.content_id”,这使它成为一个相关的子查询。我的理解是,不能使用 WITH 子句来考虑相关子查询。出于同样的原因,我也不能将此子查询作为内联视图(又名派生表)放在 FROM 子句中。
如何将条件包含一次并通过相关子查询将多个列注入结果集中?
【问题讨论】:
-
你担心的仅仅是查询文字大小还是查询性能?
-
这是个好问题。如果子查询的标准发生变化(这是一个真正的可能性),我担心以后维护这个查询。所以,是的,我担心查询文本的大小。
标签: sql oracle correlated-subquery