表格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
关于mysql - 从多个表中选择(mysql),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12266946/