SQL查询基于外键获取

时间:2018-03-02 05:55:47

标签: sql sql-server oracle

我正在尝试从parent and child_address读取数据。但是child_address没有parent_id。Query1 and Query2工作正常。如果我结合错误即将来临。子和其他表中的数据是可选的,只有父将有数据,所以我使用左连接。请帮我解决这个问题。

表格

create table parent(p_id number,name varchar(5));
create table table1(t1_id number,p_id number,t1_name varchar(5));
create table table2(t2_id number,p_id number,t2_name varchar(5));

create table child(c_id number,p_id number,c_name varchar(5));
create table child_address(ca_id number,c_id number,city varchar(5));

所需字段:

parent.name,table1.name,table2.name,child_address.city

查询1:

select parent.p_id,table1.t1_name,table2.t2_name from parent
left join table1 on parent.p_id = table1.p_id
left join table2 on parent.p_id = table2.p_id;

QUERY2:

select child.p_id,child.c_id,child_address.ca_id,child_address.city from child
left join child_address on child.c_id = child_address.c_id;

综合查询:

select a.*,b.* from (
select * from (
select parent.p_id,table1.t1_name,table2.t2_name from parent
left join table1 on parent.p_id = table1.p_id
left join table2 on parent.p_id = table2.p_id) as a
left join 
select * from (
select child.p_id,child.c_id,child_address.ca_id,child_address.city from child
left join child_address on child.c_id = child_address.c_id) as b  on a.pid = b.pid)

3 个答案:

答案 0 :(得分:1)

select    
  p.name, t1.t1_name, t2.t2_name, ca.city 
from   
  parent p   
  left join table1 t1 on t1.p_id = p.p_id   
  left join table2 t2 on t2.p_id = p.p_id   
  left join child  c  on c.p_id  = p.p_id   
  left join child_address ca on ca.c_id = c.c_id

答案 1 :(得分:1)

pid代替p_id子查询。

2.尝试在ASFROM子查询后删除JOIN keywrod,如下所示

你可以试试。

SELECT  *
FROM    ( SELECT    a.name,
                    a.t1_name,
                    a.t2_name,
                    b.city
          FROM      ( SELECT    parent.p_id ,
                                parent.name,
                                table1.t1_name,
                                table2.t2_name
                      FROM      parent
                                LEFT JOIN table1 ON parent.p_id = table1.p_id
                                LEFT JOIN table2 ON parent.p_id = table2.p_id
                    ) a
                    LEFT JOIN ( SELECT  child.p_id ,
                                        child.c_id ,
                                        child_address.ca_id ,
                                        child_address.city
                                FROM    child
                                        LEFT JOIN child_address ON child.c_id = child_address.c_id
                              )  b ON a.p_id = b.p_id
        )  a1;

SQLFiddle

答案 2 :(得分:1)

您在这里缺少一个左括号:left join select * from。它必须是:left join (select * from而不是。

无论如何,你的查询有点太复杂了。 (select * from (<query>))可以写为(<query>)。所以这应该只是:

select * from (<parent query>) p left outer join (<child query>) c on c.p_id = p.p_id;

当然,您可以对WITH子句执行相同的操作:

with p as (<parent query>), 
     c as (<child query>)
select * from p left join c on c.p_id = p.p_id;