当前位置:网站首页>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;
原网站

版权声明
本文为[Eden Garden]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010531311632.html