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
答案 0 :(得分:1)
请尝试将INNER JOIN
上的tbl_questions_votes
更改为LEFT JOIN
,因为我认为问题是否有投票都没有关系。
第二,您要同时在answares
上联接表questions
和user_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 topic和this other one