我应该如何在mysql表设计中存储问题和答案

时间:2012-07-27 07:49:35

标签: mysql database-design data-modeling

我有以下表格

  1. 用户
  2. 问题
  3. QuestionCategories
  4. 答案
  5. 我很困惑我的用户类是否应该有任何问题或答案的链接

    用户将回答表单上显示的问题。

    因此,每年对不同的问题都有不同的答案

3 个答案:

答案 0 :(得分:2)

我假设用户可以提出问题,问题可以属于某个类别,并且许多用户可以发布答案。这实际上就像stackoverflow这样的网站是什么样的。

create table user (
  user_id integer primary key,
  name varchar(40) not null
);

create table category (
  category_id integer primary key,
  category varchar(40) not null
);

create table question (
  question_id integer primary key,
  question text,
  asked_by_id integer not null,
  category_id integer not null,
  foreign key asked_by_id references user(user_id),
  foreign key category_id references categor(category_id)
);

create table answer (
  answers_id     integer not null,
  answered_by_id integer not null,
  answer text,
  primary key (answers_id, answered_by_id), -- we allow one answer per person for a question
  foreign key answers_id references question(question_id),
  foreign key answered_by_id references user(user_id)
);

然后查询:

select qu.name as asked_by,    question, category,
       au.name as answered_by, answer
from user qu                                       -- iterating through users
join question q on qu.user_id    = asked_by_id     -- joining them to their questions
join category c on c.category_id = q.category_id   -- find the category
join answer     on answers_id    = question_id     -- join by what answers this question
join user au    on au.user_id    = answered_by_id; -- looking up the user who answered it

(我没有在服务器上尝试过,所以可能会有拼写错误。请随意纠正。)

答案 1 :(得分:0)

嗯,这取决于你想做什么是有道理的。用户是否可以发布问题?如果是,请链接它。如果没有,链接没有意义,因为它会保持空虚。

答案 2 :(得分:-1)

而不是更新多行,您只需将问题及其选项和答案转换为json并存储为单个字段。