[英]Select different values from one table based on another table
So, the two tables in question: 因此,有问题的两个表:
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)
The idea is each doctor is assigned a few patients via the doctorpatient table. 想法是通过医生病人表为每个医生分配几个病人。 What I want to do is return an array of arrays, where each of the inner arrays contains this: 我想做的是返回一个数组数组,其中每个内部数组都包含以下内容:
users_id(doctor), name(doctor), surname(doctor), users_id(patient), name(patient), surname(patient)
Can this even be done using purely SQL? 甚至可以使用纯SQL完成此操作吗? I tried this: 我尝试了这个:
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
but no matter what combination of joins I try, it never comes out right. 但是无论我尝试哪种连接方式,都永远不会正确。 I tried getting the data in three separate queries and then somehow get the result I need using PHP, but I got nowhere with that. 我尝试在三个单独的查询中获取数据,然后以某种方式使用PHP获得所需的结果,但我无能为力。
Edit: What I want is this: 编辑:我想要的是:
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...
where one doctor can have multiple patients. 一个医生可以有多个病人的地方。 What my query gets me looks something like this: 我的查询让我得到的是这样的:
array(
subarray1(patient_id1,
patient_name1,
patient_surname1,
)
subarray2(patient_id2,
patient_name2,
patient_surname2,
)
etc...
But most of the data is null. 但是大多数数据为空。
I think a simple JOIN may be sufficient. 我认为简单的JOIN可能就足够了。 The OUTER JOINs appear to be causing the null values because it tries to treat the doctors as patients. 外部联接似乎导致空值,因为它试图将医生视为患者。
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
Try this: 尝试这个:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.