当前位置:网站首页>Mysql database basic operation DQL basic query

Mysql database basic operation DQL basic query

2022-07-07 16:03:00 Dark horse programmer official

 MySQL Strong performance , It is one of the most widely used databases at present , With  MySQL For learning the prototype, it is also convenient to master other databases later , Now let's give you Give a comprehensive explanation MySQL8.0 New features , From zero foundation to high-level one-stop learning , Combined with actual cases, we can gain something !

▼ MySQL8.0 introduction - Advanced learning notes :( Summary )


Catalog

Pre knowledge

Concept

application

Grammar format

Simplified syntax

Data preparation

One 、 Simple query

Operator

Operator operation - Arithmetic operator

Operator operation - Conditions of the query

Operator operation - Arithmetic operator

Operator operation - An operator

Two 、 Sort query

3、 ... and 、 Aggregate query

Aggregate query -NULL Value handling

Four 、 Group query -group by

Group query

5、 ... and 、 Paging query -limit

INSERT INTO SELECT sentence

SELECT INTO FROM sentence


Pre knowledge

Concept

  • An important function of database management system is data query , Data query should not simply return the data stored in the database , You should also filter the data as needed and determine what format the data is displayed in .
  • MySQL Provides powerful functions 、 Flexible statements to implement these operations .
  • MySQL Database usage select Statement to query data .

application

Grammar format

select 
  [all|distinct]
  < The expression of the target column 1> [ Alias ],
  < The expression of the target column 2> [ Alias ]...
from < Table or view name > [ Alias ],< Table or view name > [ Alias ]...
[where< Conditional expression >]
[group by < Name > 
[having < Conditional expression >]]
[order by < Name > [asc|desc]]
[limit < Number or list >];

Simplified syntax

select *|  Name  from  surface  where  Conditions 

Data preparation

Create databases and tables :

--  Create database 
create database if not exist mydb2;
use mydb2;
--  Create a product list :
create table product(
 pid int primary key auto_increment, --  Product id 
 pname varchar(20) not null , --  Commodity name 
 price double,  --  commodity price 
 category_id varchar(20) --  Classification of goods 
);

Add data

insert into product values(null,' Haier washing machine ',5000,'c001');
insert into product values(null,' Midea refrigerator ',3000,'c001');
insert into product values(null,' Gree air conditioning ',5000,'c001');
insert into product values(null,' Jiuyang rice cooker ’,200,'c001');

Add data :

insert into product values(null,' Woodpecker shirt ',300,'c002');
insert into product values(null,' Hengyuanxiang trousers ',800,'c002');
insert into product values(null,' Playboy jacket ',440,'c002');
insert into product values(null,' Jinba casual pants ',266,'c002');
insert into product values(null,' Hailan home sweater ',180,'c002');
insert into product values(null,' Jack Jones Sweatpants ',430,'c002');
 
insert into product values(null,' Lancome cream ',300,'c003');
insert into product values(null,' Estee Lauder essence water ',200,'c003');
insert into product values(null,' Chanel perfume ',350,'c003');
insert into product values(null,'SK-II GHb ',350,'c003');
insert into product values(null,' Shiseido foundation solution ',180,'c003');
 
insert into product values(null,' Old Beijing instant noodles ',56,'c004');
insert into product values(null,' Liangpin shop kelp silk ',17,'c004');
insert into product values(null,' Three squirrel nuts ',88,null);

One 、 Simple query

-- 1. Query all products .  
select *  from product;
-- 2. Query the product name and price . 
select pname,price from product;
-- 3. Alias query . The keywords used are as(as Can be omitted ).  
-- 3.1 Table alias : 
select * from product as p;
-- 3.2 Column alias :
select pname as pn from product; 
-- 4. Remove the repetition value .  
select distinct price from product;
-- 5. The query result is an expression ( Arithmetic query ): Put the price of all the goods +10 Yuan to display .
select pname,price+10 from product;

Operator

brief introduction

After the table structure in the database is established , The meaning of the data in the table has been determined . adopt MySQL Operator to operate , You can get another kind of data besides the table structure .

for example , There is one in the student table birth Field , This field represents the year the student was born . And use MySQL The arithmetic operator subtracts the year the student was born from the current year , So what we get is the actual age data of this student .

MySQL Support 4 Operator

  • Arithmetic operator
  • Comparison operator
  • Logical operators
  • An operator

1、 Arithmetic operator

2、 Comparison operator

3、 Logical operators

4、 An operator

Bit operators are operators that evaluate on binary numbers . Bit operations first convert operands into binary numbers , Do bit operations . Then change the result from binary to decimal .

Operator operation - Arithmetic operator

select 6 + 2;
select 6 - 2;
select 6 * 2;
select 6 / 2;
select 6 % 2;
 
--  Add... To the price of each item 10
select name,price + 10 as new_price from product;
--  Raise the price of all goods 10%
select pname,price * 1.1 as new_price from product;

Operator operation - Conditions of the query

--  The product name is “ Haier washing machine ” All information about our products :
select * from product where pname = ' Haier washing machine ';
 
--  The inquiry price is 800 goods 
select * from product where price = 800;
 
--  Inquiry price is not 800 All of our products 
select * from product where price != 800;
select * from product where price <> 800;
select * from product where not(price = 800);
 
--  The inquiry commodity price is greater than 60 All the product information of yuan 
select * from product where price > 60;
 
 
--  Inquire about the price of goods in 200 To 1000 Between all the goods 
select * from product where price >= 200 and price <=1000;
select * from product where price between 200 and 1000;

Operator operation - Arithmetic operator

--  The inquiry of commodity price is 200 or 800 All of our products 
select * from product where price = 200 or price = 800;
select * from product where price in (200,800);
 
--  Query contains ‘ pants ' All the goods of the word 
select * from product where pname like ‘% pants %';
 
--  Query to ' The sea ' All the merchandise at the beginning 
select * from product where pname like ' The sea %';
 
--  The second word is ' Cardamom ' All of our products 
select * from product where pname like '_ Cardamom %';
 
--  Inquire about category_id by null The goods 
select * from product where category_id is null;
 
--  Inquire about category_id Not for null Classified Goods 
select * from product where category_id is not null;

--  Use least For the minimum 
select least(10, 20, 30); -- 10
select least(10, null , 30); -- null
 
--  Use greatest For maximum 
select greatest(10, 20, 30);
select greatest(10, null, 30); -- null

Operator operation - An operator

Bit operators are operators that evaluate on binary numbers . Bit operations first convert operands into binary numbers , Do bit operations . Then change the result from binary to decimal .

select 3&5; --  Bit and 
select 3|5; --  Bit or 
select 3^5; --  Bit exclusive or 
select 3>>1; --  Bit shift left 
select 3<<1; --  Shift right 
select ~3;   --  Bit inversion 

Two 、 Sort query

Introduce

If we need to sort the read data , We can use MySQL Of order by Clause to set which fields and how you want to sort , Return to search results .

select 
  Field name 1, Field name 2,……
from  Table name 
order by  Field name 1 [asc|desc], Field name 2[asc|desc]……

characteristic

1.asc Represents ascending order ,desc In descending order , If you don't write the default ascending order

2.order by Used in clauses that can support a single field , Multiple fields , expression , function , Alias

3.order by Clause , Put it at the end of the query statement .LIMIT Except clause

operation

-- 1. Use price sorting ( Descending )
select * from product order by price desc;
-- 2. In price order ( Descending ) On the basis of , Sort by category ( Descending )
select * from product order by price desc,category_id asc;
-- 3. Show the price of the goods ( To repeat ), And sort ( Descending )
select distinct price from product order by price desc;

3、 ... and 、 Aggregate query

brief introduction

Before we do the query is horizontal query , They are judged line by line according to the conditions , The aggregate function query is vertical query , It calculates the values of a column , And then return a single value ; In addition, the aggregate function ignores null values .

operation

-- 1  Query the total number of items 
select count(*) from product;
-- 2  The inquiry price is greater than 200 The total number of items 
select count(*) from product where price > 200;
-- 3  The query is classified as 'c001' The sum of all the goods 
select sum(price) from product where category_id = 'c001';
-- 4  Query the maximum price of goods 
select max(price) from product;
-- 5  Query the minimum price of goods 
select min(price) from product;
-- 6  The query is classified as 'c002' The average price of all goods 
select avg(price) from product where category_id = 'c002';

Aggregate query -NULL Value handling

Introduce

1、count Function pair null Value handling

If count The argument of the function is asterisk (*), Then count the number of all records . If the parameter is a field , Excluding statistics null Number of records of value .

2、sum and avg Function pair null Value handling

These two functions ignore null Existence of value , It's like the record doesn't exist .

3、max and min Function pair null Value handling

max and min Both functions also ignore null Existence of value .

operation

--  Create table 
create table test_null( 
 c1 varchar(20), 
 c2 int 
);

--  insert data 
insert into test_null values('aaa',3);
insert into test_null values('bbb',3);
insert into test_null values('ccc',null);
insert into test_null values('ddd',6);
 
--  test 
select count(*), count(1), count(c2) from test_null;
select sum(c2),max(c2),min(c2),avg(c2) from test_null;

Four 、 Group query -group by

brief introduction :

Group query refers to the use of group by Words group query information .

Format :

select  Field 1, Field 2… from  Table name  group by  Grouping field  having  Grouping conditions ;

operation :

-- 1  Count the number of commodities in each category 
select category_id ,count(*) from product group by category_id ;

If you want to group , be SELECT After Clause , Only grouped fields and statistical functions can appear , Other fields cannot appear :

Group query

Condition filtering after grouping -having

  • If the statistical results are filtered after grouping, you must use having, Out of commission where
  • where Clause is used to filter FROM The row produced by the operation specified in clause
  • group by Clause is used to group WHERE The output of the clause .
  • having Clause is used to filter rows from grouped results

Format

select  Field 1, Field 2… from  Table name  group by  Grouping field  having  Grouping conditions ;

operation

-- 2. Count the number of commodities in each category , And only show the number greater than 4 Information about 
select category_id ,count(*) from product group by category_id having count(*) > 1;

5、 ... and 、 Paging query -limit

brief introduction :

Paging query is common in project development , Because of the amount of data , Limited display length , Therefore, the data needs to be displayed in pages . For example, data sharing 30 strip , Each page shows 5 strip , The first page shows 1-5 strip , Second page display 6-10 strip .

Format :

--  The way 1- Before display n strip 
select  Field 1, Field 2... from  indicate  limit n
--  The way 2- Pagination display 
select  Field 1, Field 2... from  indicate  limit m,n
m:  Integers , Indicates which index to start from , Calculation method  ( The current page -1)* Number of bars per page 
n:  Integers , Indicates how many pieces of data to query 

operation :

--  Inquire about product Front of table 5 Bar record  
select * from product limit 5 

--  From 4 Bar starts to show , Show 5 strip  
select * from product limit 3,5

INSERT INTO SELECT sentence

brief introduction :

Import data from one table into another , have access to INSERT INTO SELECT sentence .

Format :

insert into Table2(field1,field2,…) select value1,value2,… from Table1  perhaps :
insert into Table2 select * from Table1
Request target table Table2 There must be

SELECT INTO FROM sentence

brief introduction :

Import data from one table into another , There are two options SELECT INTO and INSERT INTO SELECT .

Format :

SELECT vale1, value2 into Table2 from Table1
Request target table Table2 non-existent , Because the table will be created automatically when inserting Table2, And will Table1 Copy field data specified in to Table2 in .
原网站

版权声明
本文为[Dark horse programmer official]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071349428395.html