2012-09-04 73 views
1

表1选择(MySQL的)

id | question 
1 | who will win the election 

表2

id | answers | question id 
1 | I will | 1 

表3

id | photo | question id 
1 | xy.gif| 1 

表4 *用户可以既建议问题,并投给他人

id | username 
1 | joe 

表5

id | vote | question_id | user_id 
1 | He | 1   | 1 

是什么会让我下面的信息在一个查询

  • T1查询。*(所有的问题)
  • T2所有的答案连接到问题
  • t3与问题相关的所有照片
  • t4每个问题的作者用户名
  • T5的问题选票(这是可能的,一些问题会不会有表决的登录用户)

  • 我的问题是最后一点,得到了选票(虽然不是所有的问题都投票通过具体登录的用户)

这里是我的查询看起来像:

  SELECT 
     poll_questions.id, 
     poll_questions.question, 
     poll_questions.qmore, 
     poll_questions.total_votes, 
     poll_questions.active, 
     poll_questions.created_at, 
     poll_answers.answer, 
     poll_answers.votes, 
     poll_answers.id AS answer_id, 
     poll_photos.photo_name_a, 
     vote_history_raw.vote, 
     users.username 

     FROM poll_questions 

     LEFT JOIN (poll_answers, poll_photos) 
      ON (poll_answers.question_id = poll_questions.id AND 
       poll_photos.question_id = poll_questions.id 
       ) 
     LEFT JOIN users ON poll_questions.author = users.id 

     INNER JOIN vote_history_raw ON users.id = vote_history_raw.user_id 

     WHERE poll_questions.active = 1 

     ORDER BY poll_questions.created_at DESC 

谢谢了!

+0

那么,有什么问题? – sumskyi

+1

作业?你试过什么了? –

+0

我无法让vote_history_raw.vote加入question_id和user_id –

回答

0

没有尝试过,但是这样做的工作?

SELECT 
    poll_questions.id, 
    poll_questions.question, 
    poll_questions.qmore, 
    poll_questions.total_votes, 
    poll_questions.active, 
    poll_questions.created_at, 
    poll_answers.answer, 
    poll_answers.votes, 
    poll_answers.id AS answer_id, 
    poll_photos.photo_name_a, 
    vote_history_raw.vote, 
    users.username 

    FROM poll_questions 

    LEFT JOIN (poll_answers, poll_photos) 
     ON (poll_answers.question_id = poll_questions.id AND 
      poll_photos.question_id = poll_questions.id 
      ) 
    LEFT JOIN users ON poll_questions.author = users.id 

    LEFT JOIN vote_history_raw ON (users.id = vote_history_raw.user_id OR users.id <> vote_history_raw.user_id AND vote_history_raw.user_id IS NOT NULL) 

    WHERE poll_questions.active = 1 

    ORDER BY poll_questions.created_at DESC 
+0

不,它没有 - 您修改的LEFT加入中有users.id,但它需要是当前用户标识而不是问题作者user_id - 我试图将其更改为一个用户,我在没有帖子的数据库(在您的#13加入替换users.id),但它没有工作 –