php - Doing multiple joins in a query MySQL -
i new mysql , having trouble figuring out.
i have 2 tables called doctors
, doctor_tags
fields doctors
: doctor_id
, doctor_name
fields doctor_tags
: id
, doctor_id
, tag_name
now specific doctor_id
need find related doctors. doctors related if have same tag_name
. once find relation need doctor_name
of these doctors back.
i lost i've got far (i sure it's wrong)
select doctors.doctor_name, doctors.doctor_id doctors inner join doctors_tags on doctors.doctor_id = doctors_tags.doctor_id ...
i konw query pretty useless know need type of join.
for whoever kind enough comeup sort of query, very thankful if explain each part of in process. :)
edit: part 2
if lets introduce table has n:n relationship between doctor_id , tag_id
table fields doctor_tags_joins
: doctor_id
,tag_id
and fields tag table change
doctors_tags
: tag_id
, tag_name
, on...
how can same thing additional table included mix.
you need join tables twice:
select distinct d1.doctor_id, d2.doctor_name doctors d1 -- first doctor's tags join doctor_tags dt1 on d1.doctor_id = dt1.doctor_id -- other doctor_tags rows same tags join doctor_tags dt2 on dt1.tag_name = dt2.tag_name -- don't list doctors related , dt1.doctor_id != dt2.doctor_id -- doctors' names join doctors d2 on dt2.doctor_id = d2.doctor_id order d1.doctor_id, d2.doctor_name
i use distinct
don't multiple rows same doctors if have multiple tags in common.
if you're looking doctors related specific doctor, rather doctors, query becomes:
select doctor_name doctor_tags dt1 join doctor_tags dt2 on dt1.tag_name = dt2.tag_name , dt1.doctor_id != dt2.doctor_id join doctors d2 on dt2.doctor_id = d2.doctor_id dt1.doctor_id = :doctor_id
where :doctor_id
placeholder given doctor. don't need first doctor
table because you're not using information table.
if want related doctor names on 1 line, use group_concat
:
select d1.doctor_id, group_concat(distinct d2.doctor_name) related_doctors doctors d1 join doctor_tags dt1 on d1.doctor_id = dt1.doctor_id join doctor_tags dt2 on dt1.tag_name = dt2.tag_name , dt1.doctor_id != dt2.doctor_id join doctors d2 on dt2.doctor_id = d2.doctor_id group d1.doctor_id
for second question, queries same, except use doctor_tags_join
instead of doctor_tags
. since you're not showing tag names in results, doctor_tags
table irrelevant.
select distinct d1.doctor_id, d2.doctor_name doctors d1 join doctor_tags_join dt1 on d1.doctor_id = dt1.doctor_id join doctor_tags_join dt2 on dt1.tag_id = dt2.tag_id , dt1.doctor_id != dt2.doctor_id join doctors d2 on dt2.doctor_id = d2.doctor_id order d1.doctor_id, d2.doctor_name
Comments
Post a Comment