我有两张桌子:
obs_structure(id, auteur_cre, dt_cre, dt_modif, description, auteur_modif, structid, tag)
和
obs_structure_element(id, auteur_cre, dt_cre, dt_modif, description, auteur_modif, optional, repetitive, suite, tag, terminal, parent_id, type_id)
这些表之间有一个链接,例如:obs_structure_element.parent_id = obs_structure.id
和obs_structure_element.type_id = obs_structure.id
。
我想提供一个特定的obs_structure.structid
并检索此结构的所有子项。我找到了一段代码并适应了我的用例:
select * from
(
select
os.id as structure_id,
os.description as structure_descr,
os.structid as structid,
os.tag as structure_tag,
ose.id as element_id,
ose.description as element_descr,
ose.optional as element_optional,
ose.repetitive as element_repetitif,
ose.suite as elements_suite,
ose.tag as element_tag,
ose.terminal as element_terminal,
ose.parent_id as element_parent_id,
ose.type_id as element_type_id
from obs_structure os
right join OBS_STRUCTURE_ELEMENT ose
on os.ID = ose.TYPE_ID
)
start with element_parent_id = (select os.id from obs_structure os where os.structid = 'BDP')
connect by PRIOR element_type_id = element_parent_id
order by element_parent_id, elements_suite;
这给了我所有选择的结构的孩子。问题是,由于我无法理解的原因,我有重复的条目(见图)。
PS:我的数据库是oracle
感谢您的帮助:)
修改
如果我们用select count(*)
替换第一个选择,我们有421个条目,但如果我们用select count(distinct(element_id))
替换,我们有260个条目似乎是我应该拥有的正确条目数....
EDIT2: 似乎我的问题可以通过这种方式解决:
select distinct structure_id,structure_descr,structid,structure_tag,element_id,element_descr,elements_suite,element_tag,element_parent_id,element_type_id from
(
select
os.id as structure_id,
os.description as structure_descr,
os.structid as structid,
os.tag as structure_tag,
ose.id as element_id,
ose.description as element_descr,
ose.suite as elements_suite,
ose.tag as element_tag,
ose.parent_id as element_parent_id,
ose.type_id as element_type_id
from obs_structure os
right join OBS_STRUCTURE_ELEMENT ose
on os.ID = ose.TYPE_ID
)
start with element_parent_id = (select os.id from obs_structure os where os.structid = 'BDP')
connect by PRIOR element_type_id = element_parent_id
order by element_parent_id, elements_suite;