SQL innerjoin 4表

时间:2015-11-08 11:26:20

标签: sql

我正在尝试制作一个页面,我可以看到谁回答了什么问题。 我有以下表格:

-(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)

现在我正在尝试制作一些内部连接查询以填充几页。

-query得到了一个问题的回答。   - 谁没有回答。

每个innerjoin查询我最终都会出错:( 有人可以帮助我吗? 我更喜欢内心连接:) 也许我的表是错的:)所有positife答案可以帮助我一个方式:)

问题是多方面的答案:标志是什么颜色 - >红白蓝/绿yelllow蓝/紫绿黄

thnx in advanced

编辑:eventulie我希望它在一个网站上实现,在那里,询问的人可以看到谁回答了什么,谁没有回答....

1 个答案:

答案 0 :(得分: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;