从4个表中获取数据的MySQL数据库问题?

时间:2018-09-05 12:10:47

标签: mysql sql join select

tbl_users

tbl_questions

tbl_answares

tbl_questions_votes

SELECT
    `tbl_users`.`email`,
    `tbl_questions`.`q_id`,
    `tbl_questions`.`question`,
    `tbl_questions`.`tags`,
    `tbl_questions`.`posted_at`,
    SUM(tbl_questions_votes.upvote) AS upvotes,
    SUM(tbl_questions_votes.downvote) AS downvotes
FROM 
    `tbl_users`
INNER JOIN 
    `tbl_answares` 
ON 
    `tbl_answares`.`user_id` = `tbl_users`.`user_id`
LEFT JOIN 
    `tbl_questions` 
ON 
    `tbl_questions`.`q_id` = `tbl_answares`.`q_id`
LEFT JOIN 
    `tbl_questions_votes` 
ON 
    `tbl_questions`.`q_id` = `tbl_questions_votes`.`q_id`
WHERE
    `tbl_users`.`user_status` = 1 AND `tbl_answares`.`user_id` = '6'
GROUP BY
    `tbl_questions`.`q_id`
ORDER BY
    `tbl_questions`.`posted_at`
DESC

上面的查询返回的是回答该问题的用户的电子邮件(另一列是正确的输出),但是,我要询问该问题的用户的电子邮件。

输出: output

预期产量

`tbl_users`.`email`, // email of user that asked the question
`tbl_questions`.`q_id`,
`tbl_questions`.`question`,
`tbl_questions`.`tags`,
`tbl_questions`.`posted_at`,
SUM(tbl_questions_votes.upvote) AS upvotes,
SUM(tbl_questions_votes.downvote) AS downvotes

1 个答案:

答案 0 :(得分:1)

请尝试将INNER JOIN上的tbl_questions_votes更改为LEFT JOIN,因为我认为问题是否有投票都没有关系。

第二,您要同时在answares上联接表questionsuser_id。我认为这没有太大意义,在我看来,您是通过users以及他们提交的所有questions来获取answares的;而预期的输出是该用户拥有questions的{​​{1}}!

所以,我认为如果您像这样加入,那就更有意义了:

answared

这将INNER JOIN tbl_answares ON tbl_answares.user_id = tbl_users.user_id INNER JOIN tbl_questions ON tbl_questions.q_id = tbl_answares.q_id LEFT JOIN tbl_questions_votes ON tbl_questions.q_id = tbl_questions_votes.q_id LEFT JOIN tbl_users usrs2 ON tbl_questions.user_id = usrs2.user_id 他的 user以及answares特定的answares和为这些{ {1}},但不排除没有questions的{​​{1}};并最终与votes一起加入,从而使您要检索的每个questions

如果您对在SQL中联接表有任何疑问,建议使用this great SO topicthis other one