Natural join and left join together in mysql
-
30-05-2021 - |
Question
I have following tables
- questions -> id, question_data, user_id
- users -> id, fname, lname
- question_connect-> id, question_id, user_id
My initial query was as follows
select questions.id, questions.question_data, users.id, users.fname from questions, users where questions.user_id = users.id limit 30
But over here, i want count of users on that question, so i tried following query
select questions.id, questions.question_data, users.id, users.fname, count(questions_connect.id) from questions, users LEFT JOIN questions_connect ON `questions`.`id` = `questions_connect`.`question_id` where questions.user_id = users.id group by `questions_connect`.`id` limit 30
this shows error
Unknown column 'questions.id' in 'on clause'
SO can we make 1 call with natural join and left join and if yes, where i am going wrong..?
Solution
Using an explicit join should sort you out:
select questions.id, questions.question_data, users.id, users.fname, count(questions_connect.id)
from questions
join users on questions.user_id = users.id
left join questions_connect on `questions`.`id` = `questions_connect`.`question_id`
group by `questions_connect`.`id`
limit 30
You're better off specifying all your joins explicitly, try to forget that implicit joins exist.
OTHER TIPS
I believe you don't need to put the quotes on the joins
ON questions.id = questions_connect.question_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow