簡體   English   中英

從多個表中選擇(mysql)

[英]selecting from multiple tables (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 

非常感謝!

沒有嘗試過,但是行得通嗎?

  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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM