1

表格1

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 

非常感谢!

4

1 回答 1

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 
于 2012-09-04T15:49:49.210 回答