search
HomeDatabaseMysql TutorialLearn basic mysql syntax
Learn basic mysql syntaxJun 23, 2017 am 11:10 AM
mysqlBasestudygrammar

Preface

## mysql

Mysql syntax--This article is learned by using Navicat Premium (database management tool) to connect mysql data.

This study mainly has two parts:

1. Create users, create databases, assign permissions to users, and delete user permissions.

2. Common data types in MYSQL

3. Table-create table, primary key, foreign key

4. Three major paradigms of database design

All the following codes are edited using mysql syntax in the new query table.

/* SQL multi-line comment*/
--SQL single-line comment

Create user: CREATE USER 'Username'@'Hostname' IDENTIFIED BY 'Password';
The hostname can be empty. If it is empty, it defaults to % permission, indicating that all hosts can connect.
Assign permissions to users: GRANT permission name ON database name. Indicates TO username@hostname
Delete user permissions: REVOKE permission name ON database name. Indicates FROM user name@host name;
##Create database : CREATE DATABASE [IF NOT EXISTS] database name [CHARACTER SET[= ] 'UTF8'];
  
Query all databases in this machine: SHOW DATABASES

Use the mydb database↓, Indicates that the following queries will target the mydb database by default
USE mydb;
##Query all data tables in the database: SHOW TABLES [FROM database]

1. Create a user, create a database, assign permissions to the user, and delete User rights.
  
1. Character type:

① CHAR(N): A string with a fixed length of N characters. If the length is not enough, spaces will be automatically filled;
② VARCHAR(N): Stores characters of variable length. Commonly used 0~255;
③ TEXT: stores variable-length strings. (Commonly used phrases to publish articles and other large paragraphs of content) 0~((2^16-1)*10^2);
   ④ TINYTEXT:0~((2^8-1)*10);
   ⑤ MEDIUMTEXT: 0~((2^24-1)*10^3);
⑥ LINGTEXT:0~((2^32-1)*10^4);
⑦ enum("male", "Female"): enumeration type, the field can only accommodate enumerated data.

2. Shaping:

① TINYINT: Unsigned 0~2^8-1 Signed -2^7~2^7-1;
② SMALLINT: Unsigned 0~2^16-1 Signed-2^15~2^15-1;
③ MEDIUMINT: Unsigned 0~2^24-1 Signed-2^23~2^23 -1;
④ INT: Unsigned 0~2^32-1 Signed -2^31~2^31-1 Most commonly used!
⑤ BIGINT: Unsigned 0~2^64-1 Signed -2^63~2^63-1;

3. Floating point type:

① FLOAT: Can be accurate to 7 significant digits after the decimal point;
② DOUBLE: Can be accurate to 15 to 16 significant digits after the decimal point;

4. Date and time data type

Note: Since time storage uses string or timestamp storage, the date type is rarely used in the database.
① DATE: Stores date and time data
② TIMESTAMP: More accurate than DATE

##2 Common data types in MYSQL
3. Table-Create table, primary key, foreign key
  
【Create table

CREATE TABLE [IF NOT EXISTS] form name (
IF NOT EXISTS can be omitted, after omitting Repeated creation error. If not omitted, it will detect whether the table already exists during creation. If the table exists, the creation statement will not be executed
Defining columns: column name data type list keywords
 )
Commonly used columns Definition keyword:
① UNSIGNED: Set the list to an unsigned column. Only columns of numeric type can be set
② AUTO_INCREMENT PRIMARY KEY sets the column to an automatic growth column. Autogrow columns must be primary keys.
③ Not NULL: Settings are listed as non -empty constraints
④ unique: Set the unique constraint. Duplicate values ​​cannot appear in this field.
​ ​ ⑤ DEFAULT: Set default value constraints.


[Primary key]

1. What are the precautions for primary key? The primary key is empty by default! Primary key default uniqueness constraint!
                                                                                                                                                                               2. How to set the primary key?
① Define in the column is settings: Age Smallint (3) Primary Key,
② Set: Primary Key (Age),

[outer key]
# [外)
# 1. What are the precautions for setting foreign keys? The types must be the same. (Numeric types require the same length and unsigned, strings require the same type, and the lengths can be different.)    ③ The field where the foreign key is set must have an index. If there is no index, an index will be automatically generated when setting the foreign key.
2. What is the syntax for setting foreign keys?
[CONSTRAINT foreign key name] FOREIGN KEY (foreign key field) REFERENCES reference table (reference field) [ON DELETE SET NULL on update CASCADE]--Set referential integrity
​ ​ ​

​ 3. Foreign Referential integrity operations for key constraints?
Reference operation: How to deal with the foreign key in the foreign key table when the reference field of the reference table is deleted or updated.
Refer to the optional value: RESTRICT refuses to delete or update the reference field; (default)
no action is the same as RESTRICT, but this instruction only takes effect in MySQL; When a field is deleted or updated simultaneously; (Foreign key table and reference table are synchronized)
            set null When a reference field in the reference table is deleted or updated, the foreign key of the foreign key table is set to null;

      



CREATE TABLE IF NOT EXISTS tb1( 
-- IF NOT EXISTS 可以省略,省略后重复创建报错.如果不省略,则创建时会检测表是否已存在,如果表存在则不再执行创建语句id INT(3),
    `name` VARCHAR(255) NOT null, -- name是系统关键字,所以使用反引号``包裹age SMALLINT(3) AUTO_INCREMENT PRIMARY KEY,
    lalala INT UNIQUE,
 height DOUBLE(3,2) DEFAULT 1.2 -- 设置默认值约束:默认值为1.2-- PRIMARY KEY(age));create table if not exists classes(
 id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  classname VARCHAR(255) NOT NULL );CREATE table if not EXISTS `user`(
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    clsId INT UNSIGNED,
    `name` VARCHAR(255) NOT NULL, CONSTRAINT user_fk_classes FOREIGN KEY (clsid) REFERENCES classes(id) ON DELETE SET NULL on update CASCADE)-- auto_increment-- 显示表结构SHOW TABLES;-- 显示表内容结构SHOW COLUMNS FROM TB1;-- 现实表的建表语句show create TABLE tb1;-- 删除表DROP TABLE IF EXISTS TB1;DROP TABLE IF EXISTS classes;DROP TABLE IF EXISTS `user`;-- 修改表名 ALTER table tb1 rename tb2;-- 修改字段 列-- alter table 表名 change 旧列名 新列名 列定义 [first|after某一列]-- first 将这个字段调整为表格第一列; after某一列: 将这个字段放到某一列后面alter table tb1 change height width VARCHAR(200) not NULL FIRST; 



-- 删除表中某一列alter table tb1 drop name;-- 新增一列:必选部分:alter table tb1 add haha DOUBLE(8,2)alter table tb1 add haha DOUBLE(8,2) DEFAULT 1.2 after age;-- 新增多列:不能调整列的位置,只能插在最后。alter table tb1 add (
    ha1 DOUBLE(3,2) UNSIGNED,
    ha2 VARCHAR(255)
);-- 同时修改多表明  rename table tb3 to tb1[,`USER`to user1];rename table tb2 to tb1,`USER`to user1;-- 增加主键约束alter table tb1 add PRIMARY KEY(id);-- 删除主键约束alter table tb1 drop PRIMARY KEY;-- 新增唯一性约束ALTER table tb1 add unique key(ha1);-- 删除唯一性约束:由于创建唯一性约束会默认创建索引,所以删除时,需删除索引ALTER table tb1 drop index ha1;    
-- 设置默认值约束:前提必须设置default 属性ALTER table tb1 alter ha1 set default 20;-- 删除默认值约束ALTER table tb1 alter haha drop default;-- 设置外键约束 必选部分  alter table tb1 add  foreign key (clsid)REFERENCES classes(id)alter table tb1 add constraint waijianming foreign key (clsid)REFERENCES classes(id) ON DELETE SET NULL on update CASCADE;-- 删除外键约束,由于常见外键时会生成索引,所以删除外键后,需要删索引。alter table tb1 drop foreign key waijianming;alter table tb1 drop INDEX waijianming;

SHOW COLUMNS FROM TB1;

4 The three major paradigms of database
 
1. First normal form (1NF): Each column (field) in the data table must be the smallest unit that cannot be split. That is to ensure the atomicity of each column.
For example: userInfo: 'Yantai City, Shandong Province 13181621008'
userads: 'Yantai City, Shandong Province' userTel: '13181621008'
2. Second Normal Form (2NF): After satisfying 1NF, the requirements : All columns in the table must depend on the primary key, and there cannot be any column that has no relationship with the primary key. In other words, a table only describes one thing.

For example: The order table can only describe order-related information, so all fields must be related to the order ID;
Related to product ID;
Therefore: order information and product information cannot appear in the same table.

3. Third Normal Form (3NF): Each column in the table must be directly related to the primary key, rather than indirectly. (Each column in the table can only depend on the primary key).
For example: In the order table, customer related information is required, after the branch customer table. In the order table, you only need to have a user ID. There cannot be other customer information. Because other user information is directly related to the user ID, not to the order ID.


[The essential difference between the second normal form and the third normal form]
is that there are no two tables. The second normal form means that one table contains the attributes of multiple different entities, so it must To be divided into multiple tables.
The third normal form requires that multiple tables have been divided. Then, one table can only have the ID (primary key) of another table, but not any other information (any other information must be used The primary key is queried in another table)
     

There may be some mistakes in the notes taken during study. Your criticism and advice are welcome.

Reflect, review, and gain something every day------------------------looking forward to a better self

The above is the detailed content of Learn basic mysql syntax. 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
图文详解mysql架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

带你把MySQL索引吃透了带你把MySQL索引吃透了Apr 22, 2022 am 11:48 AM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了mysql高级篇的一些问题,包括了索引是什么、索引底层实现等等问题,下面一起来看一下,希望对大家有帮助。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool