Cách tạo cơ sở dữ liệu trong MySQL (Tạo ra MySQL Những cái bàn)
⚡ Tóm tắt thông minh
Tạo cơ sở dữ liệu trong MySQL follows two proven paths: executing a CREATE DATABASE statement, or generating physical schemas from an ER model through MySQL Workbench forward engineering. Both approaches produce identical, production-ready tables.

Các bước tạo cơ sở dữ liệu trong MySQL
A database in MySQL is a named container for tables, views, and related objects. You can create one in two ways:
1) Bằng cách thực hiện một truy vấn SQL đơn giản
2) Bằng cách sử dụng kỹ thuật chuyển tiếp trong MySQL Workbench
As Người mới bắt đầu học SQL, trước tiên hãy xem xét phương thức truy vấn.
Cách tạo cơ sở dữ liệu trong MySQL
Đây là cách tạo cơ sở dữ liệu trong MySQL:
TẠO CƠ SỞ DỮ LIỆU là lệnh SQL được sử dụng để tạo cơ sở dữ liệu trong MySQL.
Imagine you need to create a database with the name “movies”. You can create a database in MySQL by executing the following SQL command.
CREATE DATABASE movies;
Note: You can also use the command CREATE SCHEMA instead of CREATE DATABASE.
The statement works only once. Running it again throws an error, so let’s improve the query with more parameters.
NẾU KHÔNG TỒN TẠI
Một đơn MySQL server can hold many databases. When several people share that server, you may try to create a database with the name of an existing one.
NẾU KHÔNG TỒN TẠI instructs the MySQL server to check for a database with the same name before creating it. The database is created only if the name is free; without this clause, MySQL ném một lỗi.
CREATE DATABASE IF NOT EXISTS movies;
Once the database name is safe, the next decision is how MySQL should store and compare the text inside it.
Bộ sưu tập và ký tự
A bộ ký tự decides which characters a column can store, while a đối chiếu là tập hợp của rules used in comparison and sorting. Both can be defined at four levels: server, database, table, and column.
The collation you choose depends on the character set. For instance, the latin1 character set uses the latin1_swedish_ci collation, which is the Swedish case-insensitive order.
CREATE DATABASE IF NOT EXISTS movies CHARACTER SET latin1 COLLATE latin1_swedish_ci;
For local languages such as Arabic or Chinese, select the Unicode utf8mb4 character set, which stores every Unicode character, including emoji. In MySQL 8.0, utf8mb4 is the default character set and utf8mb4_0900_ai_ci the default collation.
CREATE DATABASE IF NOT EXISTS movies CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
Bạn có thể tìm thấy danh sách tất cả các bộ sưu tập và bộ ký tự đây.
You can see the list of existing databases by running the following SQL command.
SHOW DATABASES;
With the database in place, you can now add the tables that will actually hold the records.
Cách tạo bảng trong MySQL
The CREATE TABLE command is used to create tables in a database.
As the diagram shows, every table belongs to one database. Tables are created with the TẠO BẢNG statement, which has the following syntax.
CREATE TABLE [IF NOT EXISTS] `TableName` (`fieldname` dataType [optional parameters]) ENGINE = storage Engine;
tại ĐÂY
- “CREATE TABLE” is responsible for the creation of the table in the database.
- “[IF NOT EXISTS]” is optional and only creates the table if no matching table name is found.
- “`fieldName`” is the name of the field, and “data Type” defines the nature of the data stored in it.
- “[optional parameters]” is extra information about a field, such as “AUTO_INCREMENT” or NOT NULL.
- “storage Engine” manages the table, normally InnoDB, which supports transactions and foreign keys.
MySQL Tạo bảng ví dụ
Dưới đây là một MySQL example to create a table in a database:
CREATE TABLE IF NOT EXISTS `MyFlixDB`.`Members` ( `membership_number` INT AUTO_INCREMENT , `full_names` VARCHAR(150) NOT NULL , `gender` VARCHAR(6) , `date_of_birth` DATE , `physical_address` VARCHAR(255) , `postal_address` VARCHAR(255) , `contact_number` VARCHAR(75) , `email` VARCHAR(255) , PRIMARY KEY (`membership_number`) ) ENGINE = InnoDB;
Lưu ý: chính xác MySQL từ khóa là AUTO_INCREMENT with an underscore. AUTOINCREMENT thuộc về SQLite and raises a syntax error in MySQL.
Every column carries a data type, so choose carefully: neither underestimate nor overestimate the range of data you expect.
MySQL Loại dữ liệu
Data types define the nature of the data that can be stored in a particular column of a table.
MySQL có 3 main categories of data types, namely:
- Numeric
- bản văn
- Ngày giờ
Kiểu dữ liệu số
Numeric data types are used to store numeric values. It is very important to make sure the range of your data is between the lower and upper boundaries of the numeric data type you pick.
| TINYINT( ) | -128 đến 127 bình thường 0 đến 255 KHÔNG ĐƯỢC KÝ. |
| NHỎ( ) | -32768 đến 32767 bình thường 0 đến 65535 KHÔNG ĐƯỢC KÝ. |
| TRUNG BÌNH( ) | -8388608 đến 8388607 bình thường 0 đến 16777215 KHÔNG ĐƯỢC KÝ. |
| INT( ) | -2147483648 đến 2147483647 bình thường 0 đến 4294967295 KHÔNG ĐƯỢC KÝ. |
| LỚN( ) | -9223372036854775808 đến 9223372036854775807 bình thường 0 đến 18446744073709551615 KHÔNG ĐƯỢC KÝ. |
| PHAO NỔI | Một số gần đúng nhỏ có dấu thập phân động. |
| GẤP ĐÔI( , ) | Một số lớn có dấu thập phân động. |
| SỐ THẬP PHÂN( , ) | A DOUBLE stored as a string, allowing for a fixed decimal point. Choice for storing currency values. |
Các kiểu dữ liệu văn bản
As the data type category name implies, these are used to store text values. Always make sure the length of your textual data does not exceed the maximum length of the column.
| CHAR( ) | Một phần cố định dài từ 0 đến 255 ký tự. |
| VARCHAR( ) | Một phần có độ dài thay đổi từ 0 đến 255 ký tự. |
| TINYTEXT | Một chuỗi có độ dài tối đa 255 ký tự. |
| TEXT | Một chuỗi có độ dài tối đa 65535 ký tự. |
| BÃI | Một chuỗi có độ dài tối đa 65535 ký tự. |
| VĂN BẢN TRUNG BÌNH | Một chuỗi có độ dài tối đa 16777215 ký tự. |
| VỪA BLOB | Một chuỗi có độ dài tối đa 16777215 ký tự. |
| VĂN BẢN DÀI | Một chuỗi có độ dài tối đa 4294967295 ký tự. |
| LONGBLOB | Một chuỗi có độ dài tối đa 4294967295 ký tự. |
Kiểu dữ liệu ngày và giờ
Date and time data types store calendar and clock values in a fixed format, which keeps sorting and comparison reliable.
| NGÀY | YYYY-MM-DD |
| NGÀY GIỜ | YYYY-MM-DD HH: MM: SS |
| THỜI GIAN | YYYYMMDĐHMSMSS |
| THỜI GIAN | HH: MM: SS |
Other Data Types
Apart from the above, there are some other data types in MySQL.
| ENUM | To store a text value chosen from a list of predefined text values |
| SET | Điều này cũng được sử dụng để lưu trữ các giá trị văn bản được chọn từ danh sách các giá trị văn bản được xác định trước. Nó có thể có nhiều giá trị. |
| BOOL | Đồng nghĩa với TINYINT(1), dùng để lưu trữ các giá trị Boolean |
| nhị phân | Similar to CHAR; the difference is that texts are stored in binary format. |
| BIẾN THÂN | Similar to VARCHAR; the difference is that texts are stored in binary format. |
Now let’s see a query for creating a table which uses all the data types. Study it and identify how each data type is defined in the below create table MySQL thí dụ.
CREATE TABLE `all_data_types` ( `varchar` VARCHAR( 20 ) , `tinyint` TINYINT , `text` TEXT , `date` DATE , `smallint` SMALLINT , `mediumint` MEDIUMINT , `int` INT , `bigint` BIGINT , `float` FLOAT( 10, 2 ) , `double` DOUBLE , `decimal` DECIMAL( 10, 2 ) , `datetime` DATETIME , `timestamp` TIMESTAMP , `time` TIME , `year` YEAR , `char` CHAR( 10 ) , `tinyblob` TINYBLOB , `tinytext` TINYTEXT , `blob` BLOB , `mediumblob` MEDIUMBLOB , `mediumtext` MEDIUMTEXT , `longblob` LONGBLOB , `longtext` LONGTEXT , `enum` ENUM( '1', '2', '3' ) , `set` SET( '1', '2', '3' ) , `bool` BOOL , `binary` BINARY( 20 ) , `varbinary` VARBINARY( 20 ) ) ENGINE = MYISAM;
Thực hành tốt nhất để tạo ra một MySQL Cơ sở dữ liệu
A few conventions keep your scripts readable:
- Use upper case letters for SQL keywords, i.e. “DROP SCHEMA IF EXISTS `MyFlixDB`;”
- End all your SQL commands using semicolons.
- Avoid using spaces in schema, table, and field names. Use underscores instead to separate schema, table, or field names.
- Prefer InnoDB over MyISAM for new tables, because InnoDB supports transactions, row-level locking, and foreign keys.
The query method is complete. The second route reaches the same database from a visual model instead of hand-written SQL.
Làm thế nào để tạo ra MySQL Workbench ER Diagram Forward Engineering
MySQL Workbench có các tiện ích hỗ trợ kỹ thuật chuyển tiếp. kỹ thuật chuyển tiếp is the technical term that describes the process of translating a logical model into a physical implementation automatically.
Chúng tôi đã tạo ra một sơ đồ ER trong mô hình ER lesson. We will now use that ER model to generate the SQL scripts that will create our database.
Tạo cơ sở dữ liệu MyFlix từ mô hình MyFlix ER
Step 1) Open the ER model of the MyFlix database mà bạn đã tạo trước đó.
Bước 2) Chọn kỹ sư chuyển tiếp
Click on the Database menu and select Forward Engineer.
Step 3) Connection options
The next window allows you to connect to an instance of MySQL server. Click on the stored connection drop-down list and select local host. Click Execute.
Step 4) Select the options shown below
Select the options shown below in the wizard that appears. Click Next.
Step 5) Keep the selections default and click Next
The next screen shows the summary of objects in our EER diagram. Our MyFlix DB has 5 tables. Keep the selections default and click Next.
Bước 6) Revxem tập lệnh SQL
The window below previews the SQL script that creates our database. Save the script to a *.sql file or copy it to the clipboard, then click Next.
Step 7) Commit progress
The window below appears once the database is created on the selected MySQL server instance. The tables from the ER model now exist physically on the server.
The database along with dummy data is attached. We will use this DB in the lessons that follow. Simply import it in MySQL Workbench to get started.
Bấm vào đây để tải xuống MyFlixDB







.png)