2016-02-04 23 views
0

enter image description hereMysql的更深加入

至於結果說:
我想從tbl_appointment選擇所有數據,其中USER_ID = 100
tbl_doctor

加入doctor_name我想加入第三張表tbl_document

total_type1計數(DOCUMENT_TYPE)其中DOCUMENT_TYPE = 1每個USER_ID和doctor_id對
total_type2計數(DOCUMENT_TYPE)其中DOCUMENT_TYPE = 2每個USER_ID和doctor_id對
total_type3count(document_type)其中document_type = 3每個USER_ID和doctor_id對

我想:

SELECT * FROM tbl_appointment AS main 
JOIN(
    SELECT doctor_id AS d_id,doctor_name FROM tbl_doctor 
)doctor 
ON man.doctor_id=doctor.d_id 
where user_id=100 

我很困惑加入我的第三個表,請大家幫我

回答

0

我不知道爲什麼新的SQL用戶總是試圖加入子查詢,而不是直接連接表。那裏有一些教程告訴他們這樣做嗎?

在任何情況下,您都可以像加入第二張表一樣加入第三張表。由於文件可能不存在每個醫生(我不知道你的系統),我已經使用該表LEFT OUTER JOIN

SELECT 
    APPT.user_id, 
    DR.doctor_id, 
    APPT.appointment, 
    DR.doctor_name, 
    SUM(CASE WHEN DOC.document_type = 1 THEN 1 ELSE 0 END) AS total_type1, 
    SUM(CASE WHEN DOC.document_type = 2 THEN 1 ELSE 0 END) AS total_type2, 
    SUM(CASE WHEN DOC.document_type = 3 THEN 1 ELSE 0 END) AS total_type3 
FROM tbl_appointment AS APPT 
INNER JOIN tbl_doctor DR ON DR.doctor_id = APPT.doctor_id 
LEFT OUTER JOIN tbl_document DOC ON DOC.doctor_id = DR.doctor_id 
WHERE 
    APPT.user_id = 100 
GROUP BY 
    APPT.user_id, 
    DR.doctor_id, 
    APPT.appointment, 
    DR.doctor_name 

回想一下你的結果,我意識到你正在嘗試計算每種文檔類型的數量。您可以使用上面的SUM(CASE...)聲明來完成此操作,但如果添加了文檔類型4,這將無濟於事。將結果集中的document_type加入GROUP BY列表中,並計算COUNT(*)即可。您將爲每種文檔類型獲取單獨的行,但只要您的前端處理該結果的形式,就可以更容易地展開。

0

我喜歡這種風格的SQL:

select tbl_appointment.*, 
tbl_doctor.doctor_name 
(select count(*) from tbl_document where tbl_document.user_id = tbl_appointment.user_id and tbl_document.doctor_id = tbl_appointment.doctor_id and document_type=1) as total_type1, 
(select count(*) from tbl_document where tbl_document.user_id = tbl_appointment.user_id and tbl_document.doctor_id = tbl_appointment.doctor_id and document_type=2) as total_type2, 
(select count(*) from tbl_document where tbl_document.user_id = tbl_appointment.user_id and tbl_document.doctor_id = tbl_appointment.doctor_id and document_type=3) as total_type3 
from tbl_appointment 
join tbl_doctor doc on (tbl_doctor.doctor_id = tbl_appointment.doctor_id) 

你並不需要真正加入第三個表。你可以使用子查詢select count ...