1

所以,有问题的两个表:

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)

这个想法是通过医生病人表为每个医生分配几个病人。我想要做的是返回一个数组数组,其中每个内部数组都包含:

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...

但大部分数据为空。

4

2 回答 2

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
于 2013-05-08T16:33:33.623 回答
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)
于 2013-05-08T16:42:54.507 回答