I've got 2 tables, a questions
table and an answers
table with the following example data:
+-----------------------------------+
| Questions |
+----+------------------------------+
| id | title |
+----+------------------------------+
| 1 | What is your favourite game? |
| 2 | What is your favourite food? |
+----+------------------------------+
+-------------------------------------------------+
| Answers |
+----+------------------------------+-------------+
| id | text | question_id |
+----+------------------------------+-------------+
| 1 | The Last Of Us | 1 |
| 2 | PlayerUnknowns Battlegrounds | 1 |
| 3 | Uncharted | 1 |
| 4 | KFC | 2 |
| 5 | Pizza | 2 |
+----+------------------------------+-------------+
Creating a one to many relationship as in one question can have many answers, I can do any of the following:
SELECT
id, text
FROM
answers
WHERE
question_id = 1
Or:
SELECT
answers.id, answers.text
FROM
answers
JOIN
questions
ON
answers.question_id = questions.id
WHERE
questions.id = 1
Or:
SELECT
answers.id, answers.text
FROM
questions
JOIN
answers
ON
questions.id = answers.question_id
WHERE
questions.id = 1
Which all return the following (expected) results:
+-----------------------------------+
| Results |
+----+------------------------------+
| id | text |
+----+------------------------------+
| 1 | The Last Of Us |
| 2 | PlayerUnknowns Battlegrounds |
| 3 | Uncharted |
+----+------------------------------+
Should any of them be avoided? Is there a preferred way of doing this? Just curious about the dos and don’ts of querying relationships in general really.