2015-11-08 86 views
1

我試圖做一個頁面,我可以看到誰回答什麼問題什麼問題。 我有如下表:SQL innerjoin 4表

-(poeple_who_ask) 
(id) 
(username) 

-(questions) 
(id) 
(id_who_ask) 
(question) 

-(choises) 
(id) 
(id_question) 
(choise) 

-(persons_who_answer) 
(id) 
(id_who_ask) 
(id_question) 
(username) 

-(answers) 
(id) 
(id_question) 
(id_choise) 
(id_person) 

現在我想要做一些innerjoin查詢的填補了幾頁。

- 查詢問題的答案。 - 誰沒有回答。

每innerjoin查詢我做出的錯誤結束:( 可能有人幫助我白衣呢? 我是相當新的innerjoin :) 也許我的表是錯誤的:)所有positife回答可以幫我一個方式:)

問題是多answerd,如:什麼顏色是國旗 - >紅白藍/綠上面點綴着黃色藍/紫,綠,黃

先進

編輯日Thnx:eventulie我希望它在實現提問者可以選擇的網站Ë誰也回答了什麼,誰不....

+0

請innerjoin查詢顯示你的企圖以及他們是如何失敗的。 – jochen

+0

編輯您的問題並顯示樣本數據和所需結果。 –

+0

編輯:) thnx爲提示戈登。 @jochem對不起,我做了很多搜索和谷歌搜索之前,在這裏來這裏的生活:) – hexedecimal

回答

4

你可以這樣做:

SELECT 
    q.id   AS QuestionID, 
    q.question AS Questoin, 
    ask.username AS PersonWhoAsked, 
    pa.username AS PersonWhoAnswered, 
    c.choise  AS AnswerChoice 
FROM questions AS q 
INNER JOIN people_who_ask  AS ask ON q.id_who_ask = ask.id 
INNER JOIN answers   AS a ON q.id   = a.id_question 
INNER JOIN choises   AS c ON a.id_choice = c.id 
INNER JOIN persons_who_answer AS pa ON a.id_person = pa.id 
            AND pa.id_question = q.id; 

需要注意的是,如果問題沒有答案,也不會出現在該表中,包括那些沒有答案的問題,你必須使用LEFT JOIN這樣的:

SELECT 
    q.id   AS QuestionID, 
    q.question AS Questoin, 
    ask.username AS PersonWhoAsked, 
    t.username AS PersonWhoAnswered, 
    t.choise  AS AnswerChoice 
FROM questions AS q 
INNER JOIN people_who_ask  AS ask ON q.id_who_ask = ask.id 
LEFT JOIN 
(
    SELECT a.id_question, c.choice, pa.username 
    FROM answers AS a 
    INNER JOIN choises   AS c ON a.id_choice = c.id 
    INNER JOIN persons_who_answer AS pa ON a.id_person = pa.id 
) AS t ON t.id_question = q.id; 
+0

thnx爲您的答案,今晚我會嘗試實現:) – hexedecimal

+0

thnx的答案,我現在試了一下...非常有幫助並學到了一些東西....但不是不想我想要什麼,我編輯我的問題:) thnx – hexedecimal

+0

第二個查詢惠特左連接 - >這裏的字母t來自t.choise和t.username ??? – hexedecimal