当前位置:网站首页>Basic SQL syntax i
Basic SQL syntax i
2022-06-12 09:09:00 【Eden Garden】
One 、SQL Basic grammar
1、DDL- Operating the database
-- Query all databases
SHOW DATABASES;
-- Query the creation statement of a database
SHOW CREATE DATABASE Database name ;
-- see mysql Database creation format
SHOW CREATE DATABASE mysql;
-- ------------------------------------------------------------------------------
-- Create database
CREATE DATABASE Database name ; -- Creating an existing database will report an error
-- Create database ( Judge , Create... If it doesn't exist )
CREATE DATABASE IF NOT EXISTS Database name ;
-- Create database 、 And specify the character set
CREATE DATABASE Database name CHARACTER SET Character set name ;
-- ------------------------------------------------------------------------------
-- Modify the character set of the database
ALTER DATABASE Database name CHARACTER SET Character set name ;
-- ------------------------------------------------------------------------------
-- Delete database
DROP DATABASE Database name ;
-- Delete database ( Judge , Delete... If it exists )
DROP DATABASE IF EXISTS Database name ;
-- ------------------------------------------------------------------------------
-- Query the database currently in use
SELECT DATABASE();
-- Using a database
USE Database name ;
2、DDL- Operation data sheet
-- Use mysql database
USE mysql;
-- Query all tables in the library
SHOW TABLES;
-- Query table structure
DESC Table name ;
-- Query table character set
SHOW TABLE STATUS FROM Library name LIKE ' Table name ';
-- ------------------------------------------------------------------------------
-- Create data table
CREATE TABLE Table name (
Name 1 data type 1,
Name 2 data type 2,
....
Name n data type n
);
Be careful : The last column , There is no need to add comma
/** -- data type 1. int: Integer types * age int 2. double: Decimal type * score double(5,2) * price double 3. date: date , Include only mm / DD / yyyy yyyy-MM-dd 4. datetime: date , Including month, day, hour, minute, second yyyy-MM-dd HH:mm:ss 5. timestamp: Timestamp type Including month, day, hour, minute, second yyyy-MM-dd HH:mm:ss * If you don't assign a value to this field in the future , Or assign the value to null, The current system time is used by default , To automatically assign 6. varchar: character string * name varchar(20): The biggest name 20 Characters * zhangsan 8 Characters Zhang San 2 Characters */
-- Copy table
CREATE TABLE Table name LIKE The name of the copied table ;
-- ------------------------------------------------------------------------------
-- Modify the name of the table
ALTER TABLE Table name RENAME TO New table name ;
-- Modify the character set of the table
ALTER TABLE Table name CHARACTER SET Character set name ;
-- Add a column
ALTER TABLE Table name ADD Name data type ;
-- Change data type Standard grammar
ALTER TABLE Table name MODIFY Name New data types ;
ALTER TABLE Table name CHANGE Name New column names New data types ;
-- Delete column
ALTER TABLE Table name DROP Name ;
-- ------------------------------------------------------------------------------
-- Delete data table
DROP TABLE Table name ;
-- Delete data table ( Judge , Delete... If it exists )
DROP TABLE IF EXISTS Table name ;
-- Delete data table
TRUNCATE TABLE Table name ;
3、DML-INSERT sentence
-- Add data to the specified column
INSERT INTO Table name ( Name 1, Name 2,...) VALUES ( value 1, value 2,...);
-- Add data to all columns by default
INSERT INTO Table name VALUES ( value 1, value 2, value 3,...);
-- Batch add data
INSERT INTO Table name VALUES ( value 1, value 2, value 3,...),( value 1, value 2, value 3,...),( value 1, value 2, value 3,...);
-- Batch add data to the specified column
INSERT INTO Table name ( Name 1, Name 2,...) VALUES ( value 1, value 2,...),( value 1, value 2,...),( value 1, value 2,...);
/** - matters needing attention - The number of column names and values and the data type should correspond to - Except for the number type , Data of other data types need to be quoted ( Either single or double citation is OK , Recommended single citation ) */
4、DML-UPDATE sentence
-- Modify table data syntax
UPDATE Table name SET Name 1 = value 1, Name 2 = value 2,... [where Conditions ];
-- UPDATE+JOIN
UPDATE TABLE A JOIN TABLE B SET A.VALUE=B.VALUE WHERE A.ID=B.ID
/** - matters needing attention - A condition must be added to the modification statement - If there is no condition , Then all data will be modified */
5、DML-DELETE sentence
-- Delete table data syntax
DELETE FROM Table name [WHERE Conditions ];
/** - matters needing attention - A condition must be added to the delete statement - If there is no condition , All data will be deleted InnoDB in DELETE It doesn't really delete data ,MyISAM Is the real deletion */
6、DQL- Single table query
-- The query syntax
select Field list from List of table names
where List of conditions group by Grouping field having Conditions after grouping
order by Sort limit Paging limit
-- Remove duplicate queries
SELECT DISTINCT Name 1, Name 2,... FROM Table name ;
-- Calculate the value of the column ( arithmetic )
SELECT Name 1 Operator (+ - * /) Name 2 FROM Table name ;
/* Calculate the value of the column Standard grammar : SELECT Name 1 Operator (+ - * /) Name 2 FROM Table name ; If a column is null, It can be replaced ifnull( The column you want to replace , The value you want to replace ) for example : SELECT NAME,IFNULL(stock,0)+10 FROM product; */
-- names
SELECT Name 1, Name 2,... AS Alias FROM Table name ;
7、 Conditions of the query
- Condition classification
| Symbol | function |
|---|---|
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
| = | be equal to |
| <> or != | It's not equal to |
| BETWEEN … AND … | Within a certain range ( Both contain ) |
| IN(…) | A commonplace |
| LIKE Place holder | Fuzzy query _ Any single character % More than one arbitrary character |
| IS NULL | yes NULL |
| IS NOT NULL | No NULL |
| AND or && | also |
| OR or || | perhaps |
| NOT or ! | Not , No |
-- Standard grammar
SELECT Name FROM Table name WHERE Conditions ;
-- Query inventory is greater than 20 The product information of
SELECT * FROM product WHERE stock > 20;
-- Query the product information of Huawei
SELECT * FROM product WHERE brand=' Huawei ';
-- The inquiry amount is in 4000 ~ 6000 Commodity information between
SELECT * FROM product WHERE price >= 4000 AND price <= 6000;
SELECT * FROM product WHERE price BETWEEN 4000 AND 6000;
-- The query inventory is 14、30、23 The product information of
SELECT * FROM product WHERE stock=14 OR stock=30 OR stock=23;
SELECT * FROM product WHERE stock IN(14,30,23);
-- The query inventory is null The product information of
SELECT * FROM product WHERE stock IS NULL;
-- Inventory query is not null The product information of
SELECT * FROM product WHERE stock IS NOT NULL;
-- Query the product information whose name starts with Xiaomi
SELECT * FROM product WHERE NAME LIKE ' millet %';
-- Query the product information of the mobile phone contained in the name
SELECT * FROM product WHERE NAME LIKE '% mobile phone %';
8、 Aggregate functions
- Take a column of data as a whole , Do the longitudinal calculation
- Aggregate function classification
| Function name | function |
|---|---|
| count( Name ) | Statistical quantity ( Generally, it is not null The column of ) |
| max( Name ) | Maximum |
| min( Name ) | minimum value |
| sum( Name ) | Sum up |
| avg( Name ) | Average |
-- Standard grammar
SELECT Function name ( Name ) FROM Table name [WHERE Conditions ];
-- Calculation product Total number of records in the table
SELECT COUNT(*) FROM product;
-- Get the product name with the highest price
SELECT NAME,price FROM product WHERE price = (SELECT MAX(price) FROM product);
-- Get the item name of the lowest stock
SELECT NAME,stock FROM product WHERE stock = (SELECT MIN(stock) FROM product);
-- Get the total inventory quantity
SELECT SUM(stock) FROM product;
-- Get the average commodity price of Xiaomi
SELECT AVG(price) FROM product WHERE brand=' millet ';
9、 Sort query
- Sort and sort
- Be careful : Multiple sort conditions , When the condition values of the current edge are the same , To judge the second condition
| key word | function |
|---|---|
| ORDER BY Name 1 sort order 1, Name 2 sort order 2 | Sort the specified column ,ASC Ascending ( default ) DESC Descending |
-- Standard grammar
SELECT Name FROM Table name [WHERE Conditions ] ORDER BY Name 1 sort order 1, Name 2 sort order 2;
10、 Group query 、 Paging query
-- Standard grammar
SELECT Name FROM Table name
[WHERE Conditions ] GROUP BY Group column name [HAVING Conditional filtering after grouping ] [ORDER BY Sort column names sort order ];
-- For an amount greater than 4000 Yuan goods , Group by brand , Get the total amount of each group of goods ,
-- Only show that the total amount is greater than 7000 yuan 、 And in descending order of total amount
SELECT brand,SUM(price) AS getSum FROM product
WHERE price > 4000 GROUP BY brand HAVING getSum > 7000 ORDER BY getSum DESC;
-- Standard grammar
SELECT Name FROM Table name [WHERE Conditions ] GROUP BY Group column name [HAVING Conditional filtering after grouping ]
[ORDER BY Sort column names sort order ] LIMIT Start index , Number of queries ;
-- Each page shows 2 Data
SELECT * FROM product LIMIT 0,2; -- first page Start index =(1-1) * 2
SELECT * FROM product LIMIT 2,2; -- The second page Start index =(2-1) * 2
SELECT * FROM product LIMIT 4,2; -- The third page Start index =(3-1) * 2
SELECT * FROM product LIMIT 6,2; -- Page four Start index =(4-1) * 2
Two 、 constraint
1. Concept and classification of constraints
- The concept of constraints
- Limit the data in the table , Make sure the data is correct 、 effectiveness 、 integrity !
- Classification of constraints
| constraint | explain |
|---|---|
| PRIMARY KEY | Primary key constraint |
| PRIMARY KEY AUTO_INCREMENT | Primary key 、 Automatic growth |
| UNIQUE | Unique constraint |
| NOT NULL | Non empty constraint |
| FOREIGN KEY | Foreign key constraints |
| FOREIGN KEY ON UPDATE CASCADE | Foreign key cascade update |
| FOREIGN KEY ON DELETE CASCADE | Foreign key cascade delete |
2. Primary key constraint
- Primary key constraint characteristics
- The primary key constraint contains : Non empty and the only two functions
- A table can only have one column as the primary key
- Primary keys are generally used to uniquely identify data in a table
-- Add a primary key constraint when creating a table
CREATE TABLE Table name (
Name data type PRIMARY KEY,
Name data type ,
...
);
-- Delete primary key
ALTER TABLE Table name DROP PRIMARY KEY;
-- After creating a table, add a primary key separately
ALTER TABLE Table name MODIFY Name data type PRIMARY KEY;
3. Primary key auto growth constraint
-- Add the primary key auto increment constraint when creating a table
CREATE TABLE Table name (
Name data type PRIMARY KEY AUTO_INCREMENT,
Name data type ,
...
);
-- Delete auto growth
ALTER TABLE Table name MODIFY Name data type ;
-- Add automatic growth after creating a table
ALTER TABLE Table name MODIFY Name data type AUTO_INCREMENT;
4. Unique constraint
-- Add unique constraints when creating tables
CREATE TABLE Table name (
Name data type UNIQUE,
Name data type ,
...
);
-- Delete unique constraint
ALTER TABLE Table name DROP INDEX Name ;
-- Add unique constraints after creating a table
ALTER TABLE Table name MODIFY Name data type UNIQUE;
5. Non empty constraint
-- Add a non NULL constraint when creating a table
CREATE TABLE Table name (
Name data type NOT NULL,
Name data type ,
...
);
-- Delete non empty constraints
ALTER TABLE Table name MODIFY Name data type ;
-- Add a non empty constraint after creating a table
ALTER TABLE Table name MODIFY Name data type NOT NULL;
边栏推荐
- Mysql database ignores case
- mySql学习记录——三、mysql查询语句
- Solution of hmaster process flash back after starting
- Construction of memcached cache service under Linux:
- CodeCraft-22 and Codeforces Round #795 (Div. 2) 题解
- POI library update excel picture
- Binary tree calculation problem
- Full arrangement of numbers (digital password dictionary)
- mySql学习记录——二、mySql建表命令
- Grab screen and ground glass effect
猜你喜欢
![(node:22344) [DEP0123] DeprecationWarning: Setting the TLS ServerName to an IP address is not permit](/img/c1/d56ec09663857afa52f20848aeadac.png)
(node:22344) [DEP0123] DeprecationWarning: Setting the TLS ServerName to an IP address is not permit

Redis installation test

MFS详解(四)——MFS管理服务器安装与配置

Technology cloud report: how will the industrial Internet rebuild the security boundary in 2022?

2022 melting welding and thermal cutting test questions and answers
![[computer use] how to change a computer disk into a mobile disk?](/img/ff/843f4220fcaefc00980a6edc29aebf.jpg)
[computer use] how to change a computer disk into a mobile disk?

分库分表会带来读扩散问题?怎么解决?

Notes used by mqtt (combined with source code)

Flink传入自定义的参数或配置文件

torch.logical_and()方法
随机推荐
(12) Interactive component selectable
解决当打开Unity时 提示项目已经打开,而自己之前并没有打开过(可能之前异常关闭)的问题
机器学习笔记 - 循环神经网络备忘清单
Popular understanding of time domain sampling and frequency domain continuation
Sword finger offer II 016 Longest substring without repeating characters - sliding window
Binlog in mysql:
Bash tutorial
【字符集六】宽字符串和多字节字符互转
2022 low voltage electrician retraining question bank and online simulation examination
Description of string
128. longest continuous sequence hash table
Cookies and sessions
第八章-数据处理的两个基本问题
Permission modifiers and code blocks
Use NVM to dynamically adjust the nodejs version to solve the problem that the project cannot be run and packaged because the node version is too high or too low
(十五) TweenRunner
Chapter 8 - two basic problems of data processing
Does database and table splitting cause reading diffusion problems? How to solve it?
Application method of new version UI of idea + use method of non test qualification and related introduction
Definition of polar angle and its code implementation