K
K
Konstantin Podyganov2021-01-27 20:21:52
MySQL
Konstantin Podyganov, 2021-01-27 20:21:52

What is the best way to organize data in a database?

I find it difficult to choose the option of saving data to a MySQL table:
There is a questions table that stores the question and answer options.

I can turn the options array into a view string "['first', 'second']"and then store it in the `options` cell of the questions table. And I can create another table with these options and the question_id column (but this will result in 2 queries)

Which is better?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2021-01-27
@kpodyganov

Only separate tables, and answers with questions can be obtained with one request (if there was a desire):

create table questions (
  id int primary key auto_increment,
  question varchar(255)
);

create table question_options (
  id int primary key auto_increment,
  question_id int,
  answer varchar(255)
);

select 
  q.question,
  json_arrayagg(answer) answers
from questions q
join question_options qo on qo.question_id = q.id
group by q.id, q.question
;

Result:
+=============+============================+
| question    | answers                    |
+=============+============================+
| Question 1? | ["Answer 1?", "Answer 2?"] |
+-------------+----------------------------+
| Question 2? | ["Answer 3?", "Answer 4?"] |
+-------------+----------------------------+

Check SQL query

V
Vasily Bannikov, 2021-01-27
@vabka

Better separate table

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question