因此,兩個表中的問題:從一個表基於另一個表中選擇不同的值
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...
但是大部分數據都是空的。
什麼是你想要得到什麼? – Eugene 2013-05-08 16:31:12
乍一看你的查詢看起來正確。你能展示你的期望和你得到的是什麼嗎? – Barmar 2013-05-08 16:33:53