MySQL basic operation summary

1. Database operations

(1) Create a database

CREATE DATABASE <database name>;

example:

CREATE DATABASE IF NOT EXISTS RUNOOB DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

(2) Delete the database

drop database <database name>;

(3) Select the database

use <database name>;

 

2. Data type

There are three types of data: numeric , date / time, and string (character ) types.

(1) Value types 
There are two types: strict value types and approximate value data types. 
Strict numeric types: INTEGER (INT), SMALLINT, DECIMAL, and NUMERIC. 
Approximate numeric data types: FLOAT, REAL, and DOUBLE PRECISION. 
(2) 
Five types of date / time : DATETIME (YYYY-MM-DD HH: MM: SS), DATE (YYYY-MM-DD), TIMESTAMP (YYYYMMDD HHMMSS), TIME (HH: MM: SS) and YEAR ( YYYY). 
(3) String type 
Commonly used are 
char (n) and varchar (n) such as CHAR, VARCHAR, TEXT, etc. In brackets, n represents the number of characters, not the number of bytes, such as CHAR (30) can be stored 30 characters. 
Note: Use varchar for fields that change frequently ; use char to know the fixed length ; use varchar as much as possible ; only use varchar or text if it exceeds 255 characters; do not use text where varchar can be used

 

3. Table operation

(1) Create a table

CREATE TABLE table_name (column_name_1 column_type_1, column_name_2 column_type_2.....);


example:

CREATE TABLE IF NOT EXISTS `runoob_tbl`(
    `runoob_id` INT UNSIGNED AUTO_INCREMENT,
    `runoob_title` VARCHAR(100) NOT NULL,
    `runoob_author` VARCHAR(40) NOT NULL,
    `submission_date` DATE,
    PRIMARY KEY ( `runoob_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

note:

The symbols of table names and field names are backticks. 
The PRIMARY KEY keyword is used to define the column as the primary key. 
AUTO_INCREMENT defines the column as a self-increasing attribute, which is generally used for the primary key, and the value will automatically increase by 1.

 

(2) Delete the data table

DROP TABLE table_name ;

Deleted all the data and table structure of the table, and immediately released the disk space.
Supplement: Several deletions in SQL:

(I) drop table table_name: delete all data and table structure of the table , and free up disk space immediately 
(ii) truncate table table_name: delete all data of the table , retain the table structure , and free up disk space immediately 
(iii) delete from table_name: delete all data of the table , The table structure remains unchanged, for MyISAM will immediately release the disk space, InnoDB will not release the disk space; 
(vi) delete from table_name where xxx: conditional deletion, the table structure remains unchanged, whether it is innodb or MyISAM will not release the disk Space; 
after the delete operation, using optimize table table_name will immediately free up disk space.

Note:

When you no longer need the table , use drop ; when you still want to keep the table , but want to delete all records, use truncate ; when you want to delete some records, use delete. 
delete and truncate only delete table data, drop even deletes table data and table structure together, for example, delete is a single kill, truncate is a group extinction, drop is to drop the computer. 
delete is a DML statement. If you do n’t want to commit a transaction after the operation, you can roll back. truncate and drop are DDL statements. It will take effect immediately after the operation. You cannot roll back. For example, delete is to send a WeChat message to say that you can break up. truncate and drop are slaps and rolls, you can't regret it. 
In terms of execution speed, drop> truncate> delete, for example, drop is the Shenzhou rocket, truncate is the Harmony, and delete is the bicycle.

  

4. Record operation

(1) Insert data

INSERT INTO table_name ( field1, field2,...fieldN )
VALUES
( value1, value2,...valueN );
Note: 
If the data is character type, you must use single or double quotes, such as: "value". 
If the value is all in order, the previous field can be omitted. 
The first column is designed to increase the primary key (PRINARY KEY AUTO_INCREMENT), the first column can be written as 0 or nul when adding data. 
(If you omit the field, you need to write the value of the primary key. If you write the field, you do n’t need to write the primary key field. It will increment itself.)

  

(2) Query data

SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N] [ OFFSET M]

Note:

You can use one or more tables in the query statement, use a comma (,) between the tables, and use the WHERE statement to set the query conditions. 
The SELECT command can read one or more records. Use an asterisk (*) instead, and return all the field data of the table. 
Use the WHERE statement to include any conditions. 
Use the LIMIT attribute to set the number of records returned. 
Use OFFSET to specify the data offset at which the SELECT statement starts the query. The offset is 0 by default.

(I) Limit usage
limit M: return M records
limit N, M: equivalent to limit M offset N, starting from the Nth record, return M records
example:

SELECT * FROM table LIMIT 5,10; // Retrieve the record line 6-15 
SELECT * FROM table LIMIT 95, -1; // Retrieve the record line 96-last. 
// In order to retrieve the offset from a certain offset to the record set To end all record lines, you can specify the second parameter as -1: 
SELECT * FROM table LIMIT 5; // Retrieve the first 5 record lines 
// LIMIT n is equivalent to LIMIT 0, n

(Ii) where clause

SELECT field1, field2,...fieldN FROM table_name1, table_name2...
[WHERE condition1 [AND [OR]] condition2.....

Note:

The WHERE clause is similar to the if condition in programming languages. You can use AND or OR to specify one or more conditions. 
The string comparison of MySQL's WHERE clause is not case sensitive. You can use the BINARY keyword to set the case comparison of the WHERE clause to be case sensitive. 
Such as: SELECT * from runoob_tbl WHERE BINARY runoob_author = 'runoob.com'; // Only runoob.com can be queried, RUNOOB.COM will not work. No need to add BINARY.

 

(3) Update data

UPDATE table_name SET field1=new-value1, field2=new-value2 [WHERE Clause]

Example:
Increase the age of everyone by 1:

update students set age=age+1;

Change the title with id 3 to learn C ++:

UPDATE tbl SET title='学习 C++' WHERE id=3;

UPDATE replaces a character in a field:

UPDATE table_name SET field=REPLACE(field, 'old-string', 'new-string') [WHERE Clause]

For example: replace the "C ++" of the title field value with id 3 to "Python":

UPDATE tbl SET title = REPLACE(title, 'C++', 'Python') where id = 3;

(4) Delete data

DELETE FROM table_name [WHERE Clause]

Note: If no WHERE clause is specified, all records in the MySQL table will be deleted.

 

5. Keywords

(1) Like clause

SELECT field1, field2,...fieldN FROM table_name WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'

Note:

You can use the LIKE clause in the WHERE clause. 
You can use the LIKE clause instead of the equal sign =. 
LIKE is usually used with%, similar to a meta-character search.

Example:
Get all records ending in COM in the runoob_author field in the runoob_tbl table:

SELECT * from runoob_tbl WHERE runoob_author LIKE '%COM';

 

other:

like matching / fuzzy matching will be used in combination with% and _. 
'% a' // Data ending with a 
'a%' // Data starting with a 
'% a%' // Data containing 
a'_a_ '// Three digits and the middle letter is a 
' _a '/ / Two digits and the ending letter is a 
'a_' // Two digits and the beginning letter is a

 

(2) The union operator The
UNION operator is used to join the results of more than two SELECT statements into one result set. Multiple SELECT statements will delete duplicate data.

SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions]
UNION [ALL | DISTINCT] SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions];

Note:

DISTINCT: Optional, delete duplicate data in the result set. By default, the UNION operator has deleted duplicate data, so the DISTINCT modifier has no effect on the result. 
ALL: Optional, returns all result sets, including duplicate data.

example:

Select all the different countries (only different values) 
from the "Websites" and "apps" tables : 
SELECT country FROM Websites UNION SELECT country FROM apps ORDER BY country; use UNION ALL to select all from the "Websites" and "apps" tables country (also has duplicate values): 
SELECT country FROM Websites UNION ALL SELECT country FROM apps ORDER BY country;

to sum up:

UNION statement: used to display the data queried in the same column in different tables; ( excluding duplicate data )
 UNION ALL statement: used to display the data queried in the same column in different tables; ( including duplicate data )

(3) ORDER BY sorting

SELECT field1, field2,...fieldN FROM table_name1, table_name2...
ORDER BY field1 [ASC [DESC][默认 ASC]], [field2...] [ASC [DESC][默认 ASC]]

example:

SELECT * from runoob_tbl ORDER BY submission_date ASC;
SELECT * from runoob_tbl ORDER BY submission_date DESC;

Supplement: Pinyin sorting
If the character set uses gbk (Chinese character encoding character set), add ORDER BY directly after the query statement:

SELECT * 
FROM runoob_tbl
ORDER BY runoob_title;

If the character set uses utf8 (universal code), you need to first transcode the fields and then sort:

SELECT * 
FROM runoob_tbl
ORDER BY CONVERT(runoob_title using gbk);


(4) GROUP BY grouping statement The
GROUP BY statement groups the result set according to one or more columns. We can use COUNT, SUM, AVG, and other functions on the grouped columns.

SELECT column_name, function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

Example: The
data table is grouped by name, and count how many records each person has:

WITH ROLLUP can achieve the same statistics (SUM, AVG, COUNT ...) on the basis of grouped statistical data.
Example:
Group the data table by name, and count the number of logins for each person:

SELECT name, SUM(singin) as singin_count FROM employee_tbl GROUP BY name WITH ROLLUP;


(5) Join
JOIN to join multi-table queries

INNER JOIN (inner join, or equivalent connection): Get the records of the matching relationship between the fields in the two tables. 
LEFT JOIN (Left Join): Get all records in the left table, even if there is no corresponding record in the right table. 
RIGHT JOIN: Contrary to LEFT JOIN, it is used to get all records in the right table, even if there is no corresponding record in the left table.

example:

SELECT name, COUNT(*) FROM employee_tbl GROUP BY name;

INNER JOIN (You can also omit INNER and use JOIN, the effect is the same

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;

left join is different from join. MySQL LEFT JOIN will read all the data in the left data table, even if there is no corresponding data in the right table.

SELECT a.runoob_id, a.runoob_author, b.runoob_count FROM runoob_tbl a LEFT JOIN tcount_tbl b ON a.runoob_author = b.runoob_author;

RIGHT JOIN will read all the data in the right data table, even if there is no corresponding data in the left table.

SELECT a.runoob_id, a.runoob_author, b.runoob_count FROM runoob_tbl a RIGHT JOIN tcount_tbl b ON a.runoob_author = b.runoob_author;

(6) NULL value processing
Use the SQL SELECT command and WHERE clause to read the data in the data table, but when the provided query condition field is NULL, the command may not work properly.

SELECT * FROM runoob_test_tbl WHERE runoob_count IS NULL;

Can't use = directly

select * , columnName1+ifnull(columnName2,0) from tableName;

columnName1 and columnName2 are of type int. When there is a value of null in columnName2, columnName1 + columnName2 = null, ifnull (columnName2,0) turns the null value in columnName2 to 0.

(6) The alter command
uses the alter command when modifying the data table name or modifying the data table field.
Delete, add, modify table fields

ALTER TABLE tbl DROP i; // Delete the i field of tb1 table

If there is only one field left in the data table, you cannot use DROP to delete the field.

ALTER TABLE tbl ADD i INT; // Add the i field in the table tbl and define the data type: 
ALTER TABLE tbl MODIFY c CHAR (10); // Change the type of the field c to CHAR (10) 
ALTER TABLE tbl CHANGE ij BIGINT; // Change the name of the field i to j, the type is BIGINT

Modify the table name:

ALTER TABLE tbl RENAME TO tb2;

 

(7) Transactions
Transactions are mainly used to process data with large operations and high complexity.
In MySQL, only databases or tables that use the Innodb database engine support transactions.
Transaction processing can be used to maintain the integrity of the database, ensuring that batches of SQL statements are all executed or not executed at all .
Transactions are used to manage insert, update, and delete statements

The transaction must meet four conditions (ACID): atomicity (Atomicity, or indivisibility), consistency (Consistency), isolation (Isolation, also called independence), and durability (Durability).
Atomicity: All operations in a transaction are either completed or not completed. If an error occurs during the transaction, it will be rolled back to the state before the transaction started, just like this transaction has never been The same has been done.
Consistency: a transaction beginning before and ending with the transaction after the database's integrity is not destroyed .
Isolation: The database allows multiple concurrent transactions to simultaneously read, write, and modify its data. Isolation can prevent data inconsistency due to cross-execution when multiple transactions are executed concurrently . Transaction isolation is divided into different levels, including read uncommitted, read committed, repeatable read, and serializable. Durability: After the transaction is completed, the modification of the data is permanent , even if the system fails, it will not be lost.

Under the default settings of the MySQL command line , transactions are automatically committed , that is, the COMMIT operation will be performed immediately after the SQL statement is executed.
Therefore, to explicitly start a transaction must use the command BEGIN or START TRANSACTION,
or execute the command SET AUTOCOMMIT = 0 , used to prohibit the use of automatic submission of the current session.

Transaction control statement:

BEGIN start a transaction 
ROLLBACK transaction rollback 
COMMIT transaction confirmation 
SAVEPOINT identifier, SAVEPOINT allows to create a savepoint in the transaction, a transaction can have multiple SAVEPOINT; 
RELEASE SAVEPOINT identifier delete a transaction savepoint, when there is no specified savepoint , Executing this statement will throw an exception; 
ROLLBACK TO identifier rolls back the transaction to the mark point;

Note:

Savepoint is a method of implementing "subtransaction" in database transaction processing, also known as nested transaction. The transaction can be rolled back to savepoint without affecting the changes before the savepoint is created, without giving up the entire transaction. 
The usage of ROLLBACK rollback can set the retention point SAVEPOINT, when performing multiple operations, rollback to the desired statement. 
Use SAVEPOINT 
SAVEPOINT savepoint_name; // Declare a savepoint 
ROLLBACK TO savepoint_name; // Roll back to savepoint to 
delete SAVEPOINT 
reserved points are automatically released after transaction processing is completed (execute a ROLLBACK or COMMIT).


(8) Index The
index is like the directory page of the dictionary, and the required word can be quickly found.
The index is divided into single-column index and combined index . Single-column index, that is, an index contains only a single column , a table can have multiple single-column indexes, but this is not a combined index. Composite index, that is, an index contains multiple columns .
The index is essentially a table , which stores the primary key and index fields , and points to the records of the entity table.
Index advantages and disadvantages:

Increase the search speed
 to reduce the speed of updating the table , such as table INSERT, UPDATE, and DELETE. Because when updating the table, MySQL not only saves the data, but also saves the index file . Index files 
that take up disk space while indexing.

(I)
Create index by ordinary index:

CREATE INDEX indexName ON mytable(username(length)); 

Modify the table structure (add indexes):

ALTER table tableName ADD INDEX indexName(columnName);

Specify directly when creating the table:

CREATE TABLE mytable( 
ID INT NOT NULL, 
username VARCHAR(16) NOT NULL, 
INDEX [indexName] (username(length)) 
); 

Delete the index:

DROP INDEX [indexName] ON mytable; 

(Ii) Unique index
It is similar to the previous ordinary index, except that the value of the index column must be unique, but null values ​​are allowed. If it is a combined index, the combination of column values ​​must be unique.
Create an index:

CREATE UNIQUE INDEX indexName ON mytable(username(length)); 

Modify the table structure (add indexes):

ALTER table mytable ADD UNIQUE [indexName] (username(length))

Specify directly when creating the table:

CREATE TABLE mytable( 
ID INT NOT NULL, 
username VARCHAR(16) NOT NULL, 
UNIQUE [indexName] (username(length)) 
); 

Delete the index:

DROP INDEX [indexName] ON mytable; 

Display index information:

HOW INDEX FROM table_name;

 

(9) copy the table
. Entirely copy MySQL data table, including the structure of tables, indexes, default values, etc.
steps of:
using S the HOW the CREATE TABLE command fetch create a data table (CREATE TABLE) statement , the statement contains the original data table Structure, index, etc.
Copy the contents of the table, you can use INSERT INTO ... SELECT statement to achieve.

(10) Get server metadata

SELECT VERSION () server version information 
SELECT DATABASE () current database name (or return empty) 
SELECT USER () current user name 
SHOW STATUS server status 
SHOW VARIABLES server configuration variables

  

(11) AUTO_INCREMENT
realizes automatic growth.

CREATE TABLE insect(
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id),
    name VARCHAR(30) NOT NULL,
    date DATE NOT NULL, 
    origin VARCHAR(30) NOT NULL 
);

When inserting, the value of id is 0 or NULL, the
default starting value for auto-increment and auto-increment is 1, if you want to specify from 100:

CREATE TABLE insect(
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (id),
  name VARCHAR(30) NOT NULL, 
  date DATE NOT NULL,
  origin VARCHAR(30) NOT NULL
)engine=innodb auto_increment=100 charset=utf8;

Or after the table is created successfully:

ALTER TABLE t AUTO_INCREMENT = 100;

 

(12) Duplicate data to
prevent duplicate data in the table: the
designated field is the primary key PRIMARY_KEY

CREATE TABLE person_tbl(
  first_name CHAR(20) NOT NULL,
  last_name CHAR(20) NOT NULL,
  sex CHAR(10),
  PRIMARY KEY (last_name, first_name)
);

With a unique index set, when inserting duplicate data, the SQL statement will fail to execute successfully and throw an error.
Another unique way to set up data is to add a UNIQUE index

CREATE TABLE person_tbl(
  first_name CHAR(20) NOT NULL,
  last_name CHAR(20) NOT NULL,
  sex CHAR(10),
  UNIQUE (last_name, first_name)
); 

Statistics duplicate data:

SELECT COUNT(*) as repetitions, last_name, first_name
FROM person_tbl
GROUP BY last_name, first_name
HAVING repetitions > 1;

Note:

Determine which column may contain duplicate values. 
Use COUNT (*) to list the columns in the column selection list. 
The columns listed in the GROUP BY clause. 
The HAVING clause sets the number of repetitions to be greater than 1. 
HAVING filtering

supplement:

where: Where keyword is commonly used in the database, used to filter queries in the initial table. It is a constraint statement, used to constrain data, and works before returning the result set. 
group by: Group the result set from the select query according to a field or expression to obtain a set of groups, and then extract the value of a specified field or expression from each group. 
having: Used to filter the groupings obtained by where and group by, and find out the grouping results that meet the conditions. It is a filtering statement, which is the filtering operation on the query results after the query returns the result set. 
Execution order 
select –> where –> group by–> having–> order by

Filtering duplicate data
Use the DISTINCT keyword in the SELECT statement to filter duplicate data.

SELECT DISTINCT last_name, first_name FROM person_tbl;

Use GROUP BY to read the unique data in the data table:

SELECT last_name, first_name FROM person_tbl GROUP BY (last_name, first_name);

Deduplication

CREATE TABLE tmp SELECT last_name, first_name, sex FROM person_tbl GROUP BY (last_name, first_name, sex); // Create a temporary table, 
DROP TABLE person_tbl to filter out duplicate data ; // Delete the original table 
ALTER TABLE tmp RENAME TO person_tbl; / / Change the name of the temporary table to the original table


Or:
Add INDEX (index) and PRIMAY KEY (primary key) to the data table to delete the duplicate records in the table.

ALTER IGNORE TABLE person_tbl ADD PRIMARY KEY (last_name, first_name);

  

 

Guess you like

Origin www.cnblogs.com/yq055783/p/12738369.html