MySQL table design tutorial: Create a simple question and answer table
Introduction:
In the database system, table design is a very important part. Good table design can improve the efficiency and performance of the database, making data storage and query more convenient and effective. This article will take creating a simple question and answer table as an example, introduce the table design and creation process in MySQL, and provide code examples.
1. Requirements Analysis
Before starting to design the table, we need to clarify the requirements. Suppose we need to create a question and answer table to store questions and corresponding answers.
The requirements are as follows:
Based on the above requirements, we can design the following table structure.
2. Table design
According to requirements, we can design the following table structure.
Questions:
ID | question_content |
---|---|
1 | How to design a database table? |
2 | What is the difference between primary key and foreign key? |
Answers:
ID | answer_content | question_id |
---|---|---|
1 | To design a database table, you need to consider the data types, constraints, and relationships between tables. | 1 |
2 | Primary key is used to uniquely identify a record in a table, while foreign key is used to establish a relationship between two tables. | 2 |
Another answer for question 1. | 1 |
CREATE TABLE questions ( ID INT NOT NULL AUTO_INCREMENT, question_content VARCHAR(255) NOT NULL, PRIMARY KEY (ID) );
CREATE TABLE answers ( ID INT NOT NULL AUTO_INCREMENT, answer_content VARCHAR(255) NOT NULL, question_id INT NOT NULL, PRIMARY KEY (ID), FOREIGN KEY (question_id) REFERENCES questions(ID) );
4. Insert data
After the table is created, we can insert data to test the correctness and integrity of the table. The following is sample code to insert data into the question table and answer table.INSERT INTO questions (question_content) VALUES ('How to design a database table?'), ('What is the difference between primary key and foreign key?');
INSERT INTO answers (answer_content, question_id) VALUES ('To design a database table, you need to consider the data types, constraints, and relationships between tables.', 1), ('Primary key is used to uniquely identify a record in a table, while foreign key is used to establish a relationship between two tables.', 2), ('Another answer for question 1.', 1);
Reference materials:
The above is the detailed content of MySQL table design tutorial: Create a simple question and answer table. For more information, please follow other related articles on the PHP Chinese website!