带子表的SQL查询

时间:2019-02-17 15:13:01

标签: sql oracle

我有两个表Parent和Child。

父表具有以下列

Parent_id,姓名

子表具有以下列

Parent_id(外键),标识符,标识符值

现在我要列出不同的parent_id,其名称和(子表的)identifier_value的Identifier =“ test”具有相同的identifier_value,但Identifier =“ test1”具有不同的identifier_value

即考虑一个例子

父表---

Parent_id, Name
1, XYZ
2, PQR

子表

Parent_id, Identifier, Identifier_value
1, test, value1
1, test1, ghght 
2, test, value1
2, test1, khkhgj

输出应为

1, XYZ, value1, ghght
2, PQR, value1, khkhgj

对于上例,它应返回结果,如parent_id 1和2,test具有相同的值,而test1具有不同的值

这是我到目前为止所写的内容

SELECT p.parent_id,
  p.name,
  eid.identifier_value,
  eid2.identifier_value
FROM parent p,
  child eid,
  child eid2
WHERE e.parent_id             = eid.parent_id
AND e.parent_id               = eid2.parent_id
AND eid.identifier  = 'test'
AND eid2.identifier = 'test1'
AND EXISTS
  (SELECT 1
  FROM child eid3
  WHERE eid3.identifier = 'test'
  AND eid3.value                    =eid.value
  AND eid3.parent_id             <> eid.parent_id
  AND EXISTS
    (SELECT 1
    FROM child eid4
    WHERE eid4.parent_id         = eid3.parent_id
    AND eid4.identifier = 'test1'
    AND eid3.value                 <> eid4.value
    AND eid4.identifier = eid3.identifier
    )
  )

最后一个子查询中的问题。需要一些建议。

2 个答案:

答案 0 :(得分:0)

这是您要寻找的吗?

select p.*, c1.Identifier_value, c2.Identifier_value
from parent p left join
     child c1
     on c1.parent_id = p.id and c1.identifier = 'test' left join
     child c2
     on c2.parent_id = p.id and c2.identifier = 'test2'
where c1.Identifier_value <> c2.Identifier_value;

答案 1 :(得分:0)

gordon给出的查询有什么问题,下面是您提供的示例数据的结果。

with parent_table as
(
select 1 as parent_id, 'XYZ' as name from dual
union
select 2 as parent_id, 'PQR' as name from dual
),
child_table as 
(
select 1 as parent_id, 'test' as Identifier, 'value1' as Identifier_value from dual
union
select 1 as parent_id, 'test1' as Identifier, 'ghght' as Identifier_value from dual
union
select 2 as parent_id, 'test' as Identifier, 'value1' as Identifier_value from dual
union
select 2 as parent_id, 'test1' as Identifier, 'khkhgj' as Identifier_value from dual
)
select p.*, c1.Identifier_value, c2.Identifier_value
from parent_table p left join
     child_table c1
     on c1.parent_id = p.parent_id and c1.identifier = 'test' left join
     child_table c2
     on c2.parent_id = p.parent_id and c2.identifier = 'test1'
where c1.Identifier_value <> c2.Identifier_value;

输出与问题中的预期输出相同。

1   XYZ value1  ghght
2   PQR value1  khkhgj