Home  >  Article  >  Database  >  How to create a table in mysql

How to create a table in mysql

下次还敢
下次还敢Original
2024-04-14 19:18:53429browse

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 table in mysql

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>
  • id: primary key column, automatically incrementing integer.
  • name: String column, up to 255 characters.
  • email: String column, unique value and cannot be empty.

2. Specify the column name and data type

Specify the column name and data type in brackets. Supported data types include:

  • INT: Integer
  • VARCHAR(N): Variable length string (N is the maximum length)
  • DATETIME: Date and Time
  • BOOL: Boolean value (TRUE/FALSE)

3. Set constraints

Constraints can ensure the integrity of the data and consistency. Common constraints include:

  • NOT NULL: Column cannot be empty.
  • UNIQUE: The values ​​in the column must be unique.
  • PRIMARY KEY: Specifies the primary key column, which uniquely identifies each row of the table.
  • FOREIGN KEY: Specifies an association with another table column.

4. Other options

You can also specify other options, such as:

  • DEFAULT: Specify default value.
  • COMMENT: Add comments to the table.
  • ENGINE: Specify which storage engine the table uses (for example, InnoDB, MyISAM).

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>
  • quantity column has a default value of 0. The
  • user_id and product_id columns are foreign keys that reference columns in the users and products tables.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn