2

我有大约 10 张桌子。一个具有主键的表和所有其他表通过外键连接到该单个表。例如。

Table main : 1,2,3,4,5,6,7,8
Tablechild: 1,2,3
Tableanchild: 1,3,5
Tableachild: 1,2,4,5

我想提取主表和所有其他表的完整数据,例如。

1      "tablechild data" "tableanchild data" tableachild data"
2      tablechild data                       tableachild data
3      tablechild data    tableanchild data
4 
5 
6
7
8

我使用过left join,但它提供了冗余数据。对于每个显示外键的表,请提前致谢。

$sql = "SELECT * FROM login AS jon
                        LEFT JOIN re as rec ON jon.no=rec.no
                        LEFT JOIN bio as bio ON jon.no=bio.no   
                        LEFT JOIN pon as po ON jon.no=po.no
                        LEFT JOIN rec as re ON jon.no=re.no
                        LEFT JOIN spn as sp ON jon.no=sp.no" ;

我也试过

" SELECT login.no,re.name ,re.num,bio.address,bio.phone,pon.lline,pon.set,rec.book,rec.pen,spn.rub,spn.stylo FROM login,re,bio,pon,rec,spn WHERE login.no=re.no AND login.no=bio.no  AND login.no=pon.no  AND login.no=rec.no  AND login.no=spn.no ";

我想做 SELECT Ax , By , Bz, Cd ,Cf FROM A,B,C WHERE AX is distinct as x is primary key in A and foreign key in others 。预期产出

1    B data
2    B data      C data
3                C data
4    B data      C data
5

现在我得到

   1   B data
   1   ....
   1   .......
   2   ....
   2   ......
   3
   4
   4
   5 
4

2 回答 2

0

让表A有 cloumnxyB 有xz

然后查询select * from A, B where A.x = B.x将给出冗余数据。如你所说。或者,您可以将查询编写为select A.x, A.y, B.y from A, B where A.x = B.x

于 2012-07-24T14:10:06.897 回答
0

左连接应该在这里工作

这是一个例子(我使用的是sql server,但逻辑应该完全一样)

declare @main table (pk int)

insert into @main(pk) values (1),(2),(3),(4),(5),(6),(7),(8)

declare @childA table(afk int)
declare @childB table(bfk int)
declare @childC table(cfk int)

insert into @childA(afk) values (1),(2),(3)
insert into @childB(bfk) values (1),(3),(5)
insert into @childC(cfk) values (1),(2),(4),(5)


select * from 
    @main m
    left join @childA a on m.pk = a.afk 
    left join @childB b on m.pk = b.bfk  
    left join @childC c on m.pk = c.cfk  

只要确保表是起始表并且不应该有多余的数据。

因此,在您的情况下,您的查询将类似于:

select * from 
    mainTable m
    left join childA a on m.pk = a.afk 
    left join childB b on m.pk = b.bfk  
    left join childC c on m.pk = c.cfk  
于 2012-07-24T15:16:14.620 回答