How to create a MySQL table? Use the CREATE TABLE statement to specify the table name and structure. Specify the column name and data type in parentheses. Set constraints (such as NOT NULL, UNIQUE, PRIMARY KEY) to ensure data integrity. Specify other options (such as default values, annotations, storage engines).
How to create a MySQL table
Creating a table in a MySQL database is the basic organizational unit of data. Creating a table requires the following steps:
1. Use the CREATE TABLE statement
First, use the CREATE TABLE statement to create a new table. The statement should contain the table name and the structure of the table, including column names, data types, and constraints.
For example:
<code>CREATE TABLE users ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL );</code>
2. Specify the column name and data type
Specify the column name and data type in brackets. Supported data types include:
3. Set constraints
Constraints can ensure the integrity of the data and consistency. Common constraints include:
4. Other options
You can also specify other options, such as:
For example:
<code>CREATE TABLE orders ( id INT NOT NULL AUTO_INCREMENT, user_id INT NOT NULL, product_id INT NOT NULL, quantity INT NOT NULL DEFAULT 0, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (product_id) REFERENCES products(id) );</code>
The above is the detailed content of How to create a table in mysql. For more information, please follow other related articles on the PHP Chinese website!