我有一个包含三个表的数据库:医生,办公室,专业。 医生表包含医生姓名。同样,办公室桌子包含办公地址,专业包含实践中医生的不同专业。
因为医生和办公室是多对多关系的,所以我有一个链接表j_md_ofc。同样,我有一个链接表j_md_spc,用于医生和他们的专业之间的多对多关系。
我无法创建一个查询,列出在特定办公室工作的医生及其专业。最终目标是在给定办公室的网页上显示以下内容:
从查询结果到创建网页所需的PHP是没有问题的。创建查询是我遇到的问题。可以使用简单的(?嵌套的)查询来完成,还是必须进行2次单独的查询?
答案 0 :(得分:0)
select physician_name, specialty_name, ...
from
physicians p
inner join physician_offices po
on po.physician_id = p.physician_id
inner join physician_specialities ps
on ps.physician_id = p.physician_id
inner join specialities s
on s.specialty_id = ps.specialty_id
where
po.office_id = ?
或者可能更好地猜测表/列名称:
select md.name, spc.name, ...
from
md
inner join j_md_ofc mo
on mo.md_id = md.md_id
inner join j_md_spc ms
on ms.md_id = md.md_id
inner join spc
on spc.spc_id = ms.spc_id
where
mo.ofc_id = ?
答案 1 :(得分:0)
这样的事情应该有效(尽管应该有更快的方法):
SELECT p.`name`, GROUP_CONCAT(s.name) from physician p
/* Join physician and office */
INNER JOIN j_md_ofc p2o
ON (p.id = p2o.physician_id)
/* Join speciality and physician */
INNER JOIN j_md_spc p2s
ON (p.id = p2s.physician_id)
/* Join speciality_id with speciality name */
INNER JOIN speciality s
ON (s.id = p2s.speciality_id)
/* Join office_id with office name */
INNER JOIN office o
ON (o.id = p2o.office_id)
WHERE o.name = "a"
GROUP BY p.name