【问题标题】:How to select a column from a table and another column from another table如何从一个表中选择一列,从另一个表中选择另一列
【发布时间】:2019-05-02 11:34:28
【问题描述】:

试图创建一个数据库,其中包含一个问题表和一个问题答案表。

如何选择一个问题(来自 poll_question)和该问题的答案(来自 poll_answer)?

CREATE TABLE poll_question(Id_question int primary key not null, question varchar(60));

CREATE TABLE poll_answer(Id_answer int primary key not null, answer varchar(100));

INSERT INTO poll_question(Id_questao, questao)
VALUES(1,"What kind of paper is allowed in tommorows exam?");

INSERT INTO poll_answer(Id_answer,answer)
VALUES(1,"A4 squared sheet");

INSERT INTO poll_answer(Id_answer,answer)
VALUES(2,"A4 lined sheet");

【问题讨论】:

  • 提示:INNER JOIN.
  • 您需要在“poll_answer”中使用/添加“Id_question”作为参考,作为外键建立表之间的JOIN。

标签: mysql sql mysql-workbench


【解决方案1】:

您的poll_answer 表不完整。它需要另一列来指示每个答案属于哪个问题,例如

CREATE TABLE poll_answer(Id_answer int primary key not null, Id_question int, answer varchar(100));
INSERT INTO poll_answer(Id_answer,Id_question,answer)
VALUES(1,1,"A4 squared sheet"),
(2,1,"A4 lined sheet");

然后您可以使用JOIN 找到给定问题的答案:

SELECT q.question, a.answer
FROM poll_question q
JOIN poll_answer a ON a.Id_question = q.Id_question

输出:

question                                            answer
What kind of paper is allowed in tommorows exam?    A4 squared sheet
What kind of paper is allowed in tommorows exam?    A4 lined sheet

Demo on dbfiddle

【讨论】:

    猜你喜欢
    • 2011-03-30
    • 2021-12-30
    • 2016-07-22
    • 2023-04-05
    • 2022-01-05
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多