从多个表中选择(mysql)

时间:2012-09-04 15:41:49

标签: mysql

表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 

非常感谢!

1 个答案:

答案 0 :(得分: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 
相关问题