多表的联合查询

来源:百度知道 编辑:UC知道 时间:2024/06/24 07:31:26
比如表A含cons_id,cust_id,表B含cons_id,表C含cust_id,表D含cons_id
现在如何将这四个表关联起来

表述不明确,表B和表D有区别吗?
比如表A含cons_id,cust_id,guest_id,表B含cons_id,表C含cust_id,表D含guest_id

select a.cons_id,a.cust_id,a.guest_id from a,b,c,d
where a.cons_id=b.cons_id
and a.cust_id=c.cust_id
and a.guest_id=d.guest_id

查出的结果是同时包含在B,C,D表中的A表里的记录

select * from A
,B,C,D where A.cons_id=B.cons_id
and A.cust_id=C.cust_id
and A.cons_id=D.cons_id
--------------这样得到的数据是在前张表中都同时存在cust_id,且关联表C的数据
--------
若要全部A的数据,直接用外连接:即:
select A.* from A
left join B on A.cons_id=B.cons_id
left join C on A.cust_id=C.cust_id
left join D on A.cons_id=D.cons_id

SELECT * FROM A INNER JOIN B ON A.cons_id=B.cons_id INNER JOIN C ON A.cust_id=C.cust_id INNER JOIN D ON A.cons_id=D.cons_id

where a.cons_id=b.cons_id and a.cust_id=c.cust_id and a.cons_id=d.cons_id

这样就该行,我还没试过四个表关联呢,不敢保证哦

找每个表的主键 表.主键=表.主键