gpt4 book ai didi

mysql - 从多个表中选择(mysql)

转载 作者:行者123 更新时间:2023-11-30 23:27:52 27 4
gpt4 key购买 nike

表 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com