所以,这两个表格有问题:
userinfo: id(PK), users_id(FK to users table), name, surname
doctorpatient: id(PK), doctor_id(FK to users table), patient_id(FK to users table)
这个想法是通过doctorpatient表为每位医生分配了一些患者。我想要做的是返回一个数组数组,其中每个内部数组包含:
users_id(doctor), name(doctor), surname(doctor), users_id(patient), name(patient), surname(patient)
甚至可以使用纯SQL来完成吗?我试过这个:
SELECT userinfo.users_id,
userinfo.name,
userinfo.surname,
u2.users_id,
u2.name,
u2.surname
FROM doctorpatient
RIGHT OUTER JOIN userinfo
ON doctorpatient.doctor_id = userinfo.users_id
LEFT OUTER JOIN userinfo AS u2
ON doctorpatient.patient_id = u2.users_id
但无论我尝试什么样的联接组合,它都永远不会出现。我尝试在三个单独的查询中获取数据,然后以某种方式获得我需要使用PHP的结果,但我无处可去。
编辑:我想要的是:
array(
subarray1(patient_id1,
patient_name1,
patient_surname1,
doctor_id1,
doctor_name1,
doctor_surname1)
subarray2(patient_id2,
patient_name2,
patient_surname2,
doctor_id1,
doctor_name1,
doctor_surname1)
etc...
一位医生可以有多名患者。我的查询给我看起来像这样:
array(
subarray1(patient_id1,
patient_name1,
patient_surname1,
)
subarray2(patient_id2,
patient_name2,
patient_surname2,
)
etc...
但大多数数据都是空的。
答案 0 :(得分:2)
我认为简单的JOIN可能就足够了。 OUTER JOIN似乎导致空值,因为它试图将医生视为患者。
SELECT u1.users_id AS doctor_id,
u1.name AS doctor_name,
u1.surname AS doctor_surname,
u2.users_id AS patient_id,
u2.name AS patient_name,
u2.surname AS patient_surname
FROM doctorpatient AS d JOIN userinfo AS u1 ON d.doctor_id = u1.users_id
JOIN userinfo AS u2 ON d.patient_id = u2.users_id
答案 1 :(得分:0)
试试这个:
SELECT
u.id as user_id,
u.name as user_name
u.surname as user_usrname
d.id as doc_id,
d.name as doc_name,
d.surname as doc_surname
FROM doctorpatient as dp
LEFT JOIN userinfo as u ON (dp.pacient_id = u.id)
LEFT JOIN userinfo as d ON (dp.doctor_id = d.id)