当前位置:网站首页>MySQL - SQL statement
MySQL - SQL statement
2022-06-24 08:58:00 【Storyteller】
List of articles
- Log in to the database
- notes
- sign out 、 help
- Select database use
- establish create
- Delete drop
- insert data insert
- Copy table information
- to update UPDATE
- Delete DELETE
- Clear the table truncate
- View table format
- see show
- Modify table ALTER
- Inquire about select
- Choice judgment WHERE
- Multi-table query
- The joint query UNION
- View the summary information of the current database and current connection
Log in to the database
## Ciphertext password to enter
mysql -uroot -p
## Plaintext password entry
mysql -uroot -p password
-u user name
-hIP
-p password
notes
Single-line comments “ - - ”
--
And there is a space in the comment content
-- The comment
Single-line comments “#”
# The comment
Multiline comment “/**/”
/* The comment */
Inline comments “/*! */”
/*! The comment */
sign out 、 help
operation | |
---|---|
Exit database | exit 、\q 、quit |
help | help |
Query command | help Some commands |
DDL | Data definition language | create、drop |
---|---|---|
DML | Data operation language | crud、insert、update、select |
DCL | Data control language | grant、revoke |
Select database use
mysql> use Database name ;
Database changed
mysql>
establish create
Create database
Be careful
- The database name is in English
- Do not use the same name as the original database
grammar
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
// Create common database ;[IF NOT EXISTS] Indicates when does not exist
[DEFAULT] CHARACTER SET [=] charset_name
// Set the encoding format
[DEFAULT] COLLATE [=] collation_name
Example
// Create database
CREATE DATABASE Database name ;
// be known as Database name The database for does not exist , Then create
CREATE DATABASE IF NOT EXISTS Database name ;
// be known as Database name The database for does not exist , Then create ; And the code is utf8mb4
CREATE DATABASE IF NOT EXISTS Database name CHARACTER SET utf8mb4;
Create data table
establish MySQL Data tables need the following information :
- Table name
- Table field name Column names need not be quoted
- Define each table field
CREATE TABLE Table name ( Name data type [ constraint condition ], Name data type [ constraint condition ], Name data type [ constraint condition ]);
CREATE TABLE IF NOT EXISTS Table name ( Name INT(10), Name INT(10) AUTO_INCREMENT Unique, Name INT(10) AUTO_INCREMENT PRIMARY KEY, Name INT UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL, Name INT (10) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL, Name VARCHAR(2), Name VARCHAR(2) NOT NULL, Name VARCHAR(2) NOT NULL default “m” check ( Name in ("m","f")), Name DATE, PRIMARY KEY ( Name , Name , Name ))ENGINE=InnoDB DEFAULT CHARSET=utf8;)ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4;
IF NOT EXISTS : If it doesn't exist
IF EXISTS : If there is
AUTO_INCREMENT : Define properties that are listed as self incrementing , Generally used for primary key , The value will be added automatically 1;
- Each table can only have 1 Automatic growth fields , The auto increment field is Primary key Or there is unique index
- If the auto growth field is set to non primary key, an error will be reported if no unique index is added --> id int auto_increment
NOT NULL : When operating the database, if the data entered in this field is NULL , You're going to report a mistake
PRIMARY KEY : Used to define columns as primary keys ; You can use multiple columns to define the primary key , Columns are separated by commas
- Use PRIMARY KEY After the field defines the primary key , You cannot use it to create multiple primary keys at the end ; Can only be used once
default “m” check (sgender in (“m”,“f”)) : Can only write m or f
ENGINE Set up the storage engine
CHARSET Set encoding
Create database mysqladmin
[[email protected]]# mysqladmin -u root -p create Database name Enter password:******
Copy the structure of the table
Copy structure
create table The new name of the table like Source table
Copy structure 、 data
create table The new name of the table select * from Source table
Delete drop
Delete database
Format :
drop database Database name ;
Delete data table
grammar
DROP TABLE Table name ;
mysqladmin
[[email protected]]# mysqladmin -u root -p drop Database name Enter password:******
database [y/N] y
insert data insert
- insert data character 、 date (2000-1-1) Need quotes
INSERT INTO table_name ( field1, field2,...fieldN )VALUES ( value1, value2,...valueN );
- example
INSERT INTO table_name ( field1, field2,...fieldN )VALUES ( 'value1','value2','...valueN' );INSERT INTO table_name ( field1, field2,...fieldN )VALUES ( "value1", "value2","...valueN" );
Copy table information
Same structure
insert into Table name select * from Data sheet [where];
The structure is different
insert into Table name ( Name ) select Name from Data sheet [where];
to update UPDATE
UPDATE table_name SET field1=new-value1, field2=new-value2[WHERE Column ="a"]
Delete DELETE
DELETE FROM table_name [WHERE Clause]
Clear the table truncate
truncate Table name
View table format
describe Table name ;desc Table name ;
see show
View all libraries in the database
show databases
View the tables in the library
show tables
View basic database information
show create database Database name ;+----------+----------------------------------------------------------------+| Database | Create Database |+----------+----------------------------------------------------------------+| mm | CREATE DATABASE `mm` /*!40100 DEFAULT CHARACTER SET utf8mb4 */ |+----------+----------------------------------------------------------------++----------+-------------------------------------------------------------------------------------+| Database | Create Database |+----------+-------------------------------------------------------------------------------------+| mh | CREATE DATABASE `mh` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */ |+----------+-------------------------------------------------------------------------------------+
View the creation information of the table
show create table Table name ;+-------+--------------------------------------------------------------------------------------------------+| Table | Create Table |+-------+--------------------------------------------------------------------------------------------------+| zw | CREATE TABLE `zw` ( `id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(20) DEFAULT NULL,`sex` varchar(5) DEFAULT ' male ',PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci|+-------+--------------------------------------------------------------------------------------------------+
Modify table ALTER
ALTER {DATABASE | SCHEMA} [db_name]ALTER {DATABASE | SCHEMA} db_name UPGRADE DATA DIRECTORY NAME [DEFAULT] CHARACTER SET [=] charset_name // Modify character set [DEFAULT] COLLATE [=] collation_name
Modify the character set of the database
- View character set
show variables 1ike'characeer%';
- Modify database character set
alter database testdb character set utf8;alter database testdb default character set utf8;// Modify the character set of the database , And set as the default character set , All tables in the database will inherit this character set
Modify the name of the table
- Use ALTER TABLE Use in statement RENAME Clause to implement
# Try the following example to put the data table testalter_tbl Rename it to alter_tbl:ALTER TABLE testalter_tbl RENAME TO alter_tbl;
Add columns
ALTER TABLE Table name ADD Name INT [ constraint condition ];## The default value is 0ALTER TABLE Table name ADD Name INT default 0;
- Location
- Columns are added to the end of the data table fields by default
- FIRST ( Set the first column )
- AFTER Field name ( Set after a field )
ALTER TABLE Table name ADD Name INT FIRST;ALTER TABLE Table name ADD Name INT AFTER Name ;
Try the following ALTER TABLE sentence , After successful execution , Use SHOW COLUMNS See changes in table structure
Delete table fields
If there is only one field left in the data table, it cannot be used DROP To delete fields
The following command is used ALTER Orders and DROP Clause to delete the i Field
ALTER TABLE Table name DROP Name ;
Modify column type
- Modification type MODIFY
ALTER TABLE Table name MODIFY Name new type [ constraint condition ];
Change the name type CHANGE
- stay CHANGE After keyword , Next comes the field name you want to modify , Then specify the new field name and type
ALTER TABLE testalter_tbl CHANGE Old column names New column names new type [ constraint condition ];
Modify field defaults
- Use ALTER To change the default value of the field
ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
- Use ALTER Orders and DROP Clause to delete the default value of the field
ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
Modify data table type , have access to ALTER Orders and TYPE Clause
** Be careful :** You can use... To view data table types SHOW TABLE STATUS sentence .
ALTER TABLE testalter_tbl ENGINE = MYISAM;SHOW TABLE STATUS LIKE
Delete table constraints
- Delete not null constraint
alter table Table name modify Name type [ constraint ];
- Delete unique constraint
alter table Table name drop index Unique constraint name ;
- Delete primary key constraint
alter table Table name drop primary key;
- Delete foreign key constraint
alter table Table name drop foreign key Foreign key name ;
ALTER TABLE Yes Null The effect of values and defaults
- When you modify fields , You can specify whether to include values or whether to set default values
- If you don't set the default value ,MySQL It will automatically set the default value of this field to NULL
# Specified field j by NOT NULL And the default value is 100ALTER TABLE testalter_tbl MODIFY j BIGINT NOT NULL DEFAULT 100;
Inquire about select
grammar
SELECT Name , Name FROM database . Table name , database . Table name [WHERE Conditions ][LIMIT N][ OFFSET M]
* wildcard Represents all columns
You can query multiple tables using , separate
SELECT Command can read One or more records .
You can use LIMIT Property to set the number of records returned .
You can go through OFFSET Appoint SELECT Statement start query data offset . By default, the offset is 0.
Query current user
select user();
Querying the current database
select database()
View version
select version();
Choice judgment WHERE
grammar
SELECT surface . Name [, surface . Name ,...] FROM surface [, surface ,...] [WHERE Conditions ] [GROUP BY Name ] [HAVING Conditions ] [ORDER BY .....] [LIMIT .......]
SELECT Name , Name ,... FROM Table name 1, Table name 2...WHERE Conditions
Conditions
WHERE Name <100WHERE Name is nullWHERE Name <=>nullWHERE Name is not nullWHERE Name IN (1,2,3)WHERE Name LIKE "3%"WHERE Name IN (1,2,3)
- You can use AND perhaps OR Specify one or more conditions
WHERE Conditions 1 AND Conditions 2.....WHERE Conditions 1 OR Conditions 2.....
The examples in the following table assume A by 10, B by 20
The operator | describe | example |
---|---|---|
= | Equal sign , Check if two values are equal , If equal returns true | (A = B) return false |
<=> | Safety equal sign , It is equal to | (A = B) return false |
<>, != | It's not equal to , Check if two values are equal , If not equal return true | (A != B) return true |
> | More than no. , Check whether the value on the left is greater than the value on the right , If the value on the left is greater than the value on the right, return true | (A > B) return false |
< | Less than no. , Check if the value on the left is less than the value on the right , If the value on the left is less than the value on the right, return true | (A < B) return true |
>= | Greater than or equal to , Check whether the value on the left is greater than or equal to the value on the right , If the value on the left is greater than or equal to the value on the right, return true | (A >= B) return false |
<= | Less than or equal to sign , Check whether the value on the left is less than or equal to the value on the right , If the value on the left is less than or equal to the value on the right, return true | (A <= B) return true |
- If the given condition does not have any matching records in the table , So the query doesn't return any data
List query IN
Name IN ( list ) Name NOT IN ( list )
- Try not to use ,in Will abandon the index , Perform a full table scan
Fuzzy query LIKE
Name LIKE ‘3%’
- Give up the index , A full table query , Low efficiency
Symbol | explain |
---|---|
‘a%’ | With a start |
‘%a%’ | contain a |
‘_a%’ | The second letter is a |
- **% ** Represents any number of arbitrary characters
- _ Represents a character
Regular expressions regexp
Name regexp '^root'
Range queries BETWEEN
Name between 1000 AND 1500
- Closed interval
Sort ORDER BY
SELECT Name , Name ,... FROM Table name 1, Table name 2...ORDER BY Name [ASC [DESC][ Default ASC]], [field2...] [ASC [DESC][ Default ASC]]
- ASC Ascending 、 DESC Descending
grouping GROUP BY
SELECT column_name, function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_name;
- Put the same results in a group
- We can use... On grouped columns COUNT, SUM, AVG, Such as function .
SELECT sex,count(sex) from gxsf group by sex;
Screening HAVING
SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator value;
Pagination LIMIT
SELECT * FROM COMPANY LIMIT Number of pieces ;SELECT * FROM COMPANY LIMIT The starting position , Number of pieces ;
SELECT * FROM COMPANY LIMIT 4;SELECT * FROM COMPANY LIMIT 4,4;
where and having Then there are screening criteria , But there is a difference :
where stay group by front , having stay group by after
Aggregate functions (avg、sum、max、min、count), Cannot be placed as a condition on where after , But you can put it in having after
operation
operation | result | explain |
---|---|---|
SELECT 100+80 | 180 | Perform normal operations |
SELECT 100+‘80’ | 180 | Convert characters to numbers , Carry out operations |
SELECT 100+‘abc’ | 100 | Convert characters to numbers , Cannot be converted 0 |
SELECT ‘THIS’+‘IS’ | 0 | Convert characters to numbers , Cannot be converted 0 |
SELECT NULL+80 | NULL | One of the values is NULL, The result is NULL |
Multi-table query
- No relation is specified in the query , The database could not determine the association relationship , Just match them all , There will be Cartesian product
select Table name . Name , Table name . Name from Table name , Table name where Table name . Name = Table name . Name ;
Connect
Internal connection
- INNER JOIN( Internal connection , Or equivalent connection ): Get the records of field matching relationship in two tables
select Table name . Name , Table name . Name from Table name [inner] join Table name on( Table name . Name = Table name . Name );
SELECT a.runoob_id, a.runoob_author, b.runoob_count FROM runoob_tbl a INNER JOIN tcount_tbl b ON a.runoob_author = b.runoob_author; above SQL Statement is equivalent to :SELECT a.runoob_id, a.runoob_author, b.runoob_count FROM runoob_tbl a, tcount_tbl b WHERE a.runoob_author = b.runoob_author;
External connection
- **LEFT JOIN( Left connection ):** Mainly in the left table , Show all , Even if there is no matching record on the right
- **RIGHT JOIN( The right connection ):** Get all the records in the right table , Even if the left table does not have a matching record
select Table name . Name , Table name . Name from Table name left join Table name on( Table name . Name = Table name . Name );
select Table name . Name , Table name . Name from Table name right join Table name on( Table name . Name = Table name . Name );
Self join
- The table itself is associated with itself :
- The result of each query is also a table
surface | ||
---|---|---|
id | name | up_id |
1 | The Internet | null |
2 | linux | null |
3 | Router | 1 |
4 | Switch | 1 |
select inter.name,a.name upfrom inter left join (select id,name from inter where up_id is null) a on (inter.up_id=a.id)where up_id is not null;
Subquery
select * from Table name where Name =(select Name from Table name [where])
select * from Table name ,select Name from Table name [where]
The joint query UNION
describe
MySQL UNION Operators are used to connect more than two SELECT The results of a statement are combined into a set of results . Multiple SELECT Statement will remove duplicate data .
- The number of columns in two query statements should be the same
grammar
SELECT expression1, expression2, ... expression_nFROM tables[WHERE conditions]UNION [ALL | DISTINCT]SELECT expression1, expression2, ... expression_nFROM tables[WHERE conditions];
Parameters
- DISTINCT: Optional , Delete duplicate data in result set . By default UNION The operator has removed the duplicate data , therefore DISTINCT Modifiers have little effect on the results .
- ALL: Optional , Return all result sets , Contains duplicate data .
View the summary information of the current database and current connection
status
status--------------mysql Ver 14.14 Distrib 5.7.26, for Win64 (x86_64)Connection id: 7Current database: mmCurrent user: [email protected]: Not in useUsing delimiter: ;Server version: 5.7.26 MySQL Community Server (GPL)Protocol version: 10Connection: localhost via TCP/IPServer characterset: utf8Db characterset: utf8mb4Client characterset: utf8Conn. characterset: utf8TCP port: 3306Uptime: 3 hours 10 min 28 secThreads: 1 Questions: 42 Slow queries: 0 Opens: 340 Flush tables: 1 Open tables: 37 Queries per second avg: 0.003--------------
Currently linked id No. whether the currently linked login user of the currently selected database used ss! The line terminator of the current session is a semicolon mysql Version is mariadb Branch current mysql The version number of the server the link type used by the protocol version , Connect through the socket file of this computer. The character type used by the server is the current character type used by the database mysql The character type used by the client the character type used by the current link the start time of the socket file path database
replace
边栏推荐
猜你喜欢
KaFormer个人笔记整理
4274. suffix expression
Prompt code when MySQL inserts Chinese data due to character set problems: 1366
How to configure environment variables and distinguish environment packaging for multi terminal project of uniapp development
Pymysql inserts data into MySQL and reports an error for no reason
[pytoch basic tutorial 31] youtubednn model analysis
4275. Dijkstra sequence
À propos de ETL il suffit de lire cet article, trois minutes pour vous faire comprendre ce qu'est ETL
【Pytorch基础教程31】YoutubeDNN模型解析
Database migration from PostgreSQL to MySQL
随机推荐
【MySQL从入门到精通】【高级篇】(一)字符集的修改与底层原理
input的聚焦后的边框问题
Sword finger offer 55 - I. depth DFS method of binary tree
打印出来的对象是[object object],解决方法
PM2 deploy nuxt3 JS project
Telnet port login method with user name for liunx server
工具类
threejs辉光通道01(UnrealBloomPass && layers)
【NOI模拟赛】寄(树形DP)
Data middle office: a collection of middle office construction architectures of large domestic factories
数据中台:民生银行的数据中台实践方案
Fast and slow pointer series
数据中台:中台实践与总结
WebRTC系列-网络传输之5选择最优connection切换
ZUCC_ Principles of compiling language and compilation_ Experiment 0607 grammar analysis ll analysis
leetcode——错误的集合
I heard that you are still spending money to buy ppt templates from the Internet?
關於ETL看這篇文章就够了,三分鐘讓你明白什麼是ETL
[force deduction 10 days SQL introduction] Day3
opencv最大值滤波(不局限于图像)