我有一个表A与表B有一对多的关系。表B与表C有多对多的关系,与表D的另一个多对多关系使用连接表。现在我有一个表A的id,我想用它来获取表B及其所有连接。这是一个简单选择的子查询就足够了吗?
SELECT
tableB.id,
tableC.id,
tableD.id
from
TableB tableB
LEFT JOIN TableC tableC ON tableB.id = tableC.id
LEFT JOIN TableD tableD ON tableB.id = tableD.id
where
tableB.tableAId = :id
这是对的吗?
答案 0 :(得分:0)
你会加入。如果您想在结果中使用A,那么:
select a.*, b.*, c.*, d.*
from a
join b on b.id_a = a.id_a
left join bc on bc.id_b = b.id_b -- bridge table b <-> c
left join c on c.id_c = bc.id_c
left join bd on bd.id_b = b.id_b -- bridge table b <-> d
left join d on d.id_d = bd.id_b
where a.id = ?
如果您不想在结果中使用A,那么:
select b.*, c.*, d.*
from b
left join bc on bc.id_b = b.id_b
left join c on c.id_c = bc.id_c
left join bd on bd.id_b = b.id_b
left join d on d.id_d = bd.id_b
where b.id_a = ?
如果你只想要Bs至少有一个匹配的C和D,那么使用内连接而不是外连接。