liquidtabs
liquidtabs

Reputation: 5

select statement retrieving data from 2 tables

I have a list of clickable questions from which I'm looking to open in a new page and also display a list of options to select from a bit like a quiz or test.

So lets say in the database TableQuestions has the questions saved and TableAnswers has the possible options saved. The Answers table also includes the ID from the Questions table to determine what options are associated with each question.

However when I click the on a question it is displaying all the questions and all the answers from the database where I just want to display the question that I have clicked and the answers which have the same ID as the question.

This is my SELECT statement:

("SELECT tableQuestions.*, tableAnswers.* FROM tableQuestions, tableAnswers     WHERE tableQuestions.question_id=tableAnswers.question_id");

Can anyone assist with this? Thanks

Upvotes: 0

Views: 25

Answers (2)

Emil Alkalay
Emil Alkalay

Reputation: 496

As addition to Yossi's answer: You should use LEFT JOIN, insdead of INNER JOIN. This will allow you to display the questions which don't have answers.

Upvotes: 0

Yossi Vainshtein
Yossi Vainshtein

Reputation: 3985

Seems like you forgot to add the Id of clicked question in the SQL, so you get all questions.

Also, what you do here (brining data from 2 tables) is called joining tables, and the better syntax for this is with JOIN ... ON in the FROM part.

SELECT tableQuestions.*, tableAnswers.* FROM tableQuestions INNER JOIN tableAnswers
 ON tableQuestions.question_id=tableAnswers.question_id 
WHERE tableQuestions.question_id = <id>

Upvotes: 1

Related Questions