当前位置:网站首页>MySQL basic operation -dql
MySQL basic operation -dql
2022-07-05 12:12:00 【ziyi813】
MySQL Basic operation -DQL
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 .
- keyword :select
Grammar format
-- Basic grammar
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 >];
-- Concise grammar
select *| Name from Table name where Conditional expression
-- Example
select * from student; -- Query all fields and columns of the whole table
select * from student where id = 1; -- accord with ID=1
select id,name from student ; -- Query all the data , Display only id and name Column
The data sample :
create database if not EXISTS mydb2;
use mydb2;
create table product(
pid int(6) PRIMARY KEY auto_increment,
pname VARCHAR(20) not null,
price double,
category_id varchar(20)
);
INSERT INTO product values(null, ' shirt ', 300, 'c002');
INSERT INTO product values(null, ' Trousers for ', 800, 'c002');
INSERT INTO product values(null, ' Playboy jacket ', 100, 'c002');
INSERT INTO product values(null, ' fleece ', 200, 'c002');
INSERT INTO product values(null, ' Motion pants ', 100, 'c002');
INSERT INTO product values(null, ' Adie shoes ', 900, 'c002');
INSERT INTO product values(null, ' Face cream ', 800, 'c003');
INSERT INTO product values(null, ' Essence water ', 100, 'c003');
INSERT INTO product values(null, ' Chanel ', 200, 'c003');
INSERT INTO product values(null, 'SK-II GHb ', 100, 'c003');
INSERT INTO product values(null, ' Foundation make-up ', 900, 'c003');
INSERT INTO product values(null, ' instant noodles ', 10, 'c004');
INSERT INTO product values(null, ' kelp ', 20, 'c004');
INSERT INTO product values(null, ' The three little squirrels ', 80, 'c004');
Inquire about SELECT
1、 Simple query
-- Query all
select * from product;
-- Query commodity name and commodity classification pname,category_id
select panme,category_id from product;
-- Column alias
select pname, price from product;
-- Remove the repetition value distinct key word
select distinct price from product;
-- The query result is an expression ( Arithmetic query ), Put the price of all the goods +10 No operation
select pname, price+10 from product;
2、 Operator
brief introduction
After the table structure in the database is determined , 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 .
MySQL Support 4 Operator
- Arithmetic operator :+ - * / perhaps DIV % perhaps MOD
- Comparison operator
- Logical operators
- An operator
Arithmetic operator
Arithmetic operator | explain |
---|---|
+ | Addition operation |
- | Subtraction |
* | Multiplication |
/ perhaps DW | Division operations , Returnee |
% perhaps MOD | The remainder , Returns the remainder |
Comparison operator
Comparison operator | explain |
---|---|
= | be equal to |
< and <= | Less than and less than equal to |
> and >= | Greater than and greater than or equal to |
<=> | Safe is equal to , Both opcodes are NULL when , The resulting value by 1; And when an opcode is NULL when , The resulting value by 0 |
<> perhaps != | It's not equal to |
IS NULL perhaps ISNULL | Judge a value Is it NULL |
IS NOT NULL | Judge a value If not for NULL |
LEAST | When there are two or more parameters , Return minimum |
GREATEST | When there are two or more parameters , Return maximum |
BETWEEN AND | Judge whether a value falls between two values Between |
IN | Judge a value yes IN Any value in the list |
NOT IN | Judge a value No IN Any value in the list |
LIKE | Wildcard match |
REGEXP | Regular Expression Matching |
Logical operators
Logical operators | explain |
---|---|
NOT perhaps ! | Logic is not |
AND perhaps && | Logic and |
OR perhaps || | Logic or |
XOR | Logical XOR |
An operator
Bitwise operators are operators that evaluate on binary , Will first convert the operand to binary , Do bit operations . Then convert the calculation result from binary to decimal . Rarely use .
An operator | explain |
---|---|
! | Press bit or |
& | Bitwise AND |
^ | Bitwise XOR |
<< | Move left according to position |
>> | Right shift to position |
~ | According to the not , Invert all bits |
3、 Sort query
key word :order by
- asc Represents ascending order ,desc In descending order , If you don't write, the default is ascending
- order by Used in clauses that can support a single field , Multiple fields , expression , function , Alias
- order by Clause , Put it at the end of the query statement .limit Except clause
Example :
-- Use price sorting
select * from product order by price desc;
-- On the basis of price ranking , Sort by category
select * from product order by price desc, category_id asc;
-- Show the price of the goods ( To repeat ), And sort
select distinct price from product order by price desc;
4、 Aggregate query
The queries described above are horizontal queries , They are judged line by line according to the conditions , Using aggregate query is vertical query , It is the value of a column Calculate , And then return a single value ; In addition, aggregate queries ignore null values .
Aggregate functions | effect |
---|---|
count() | The specified column of statistics is not NULL The number of record lines |
sum() | Calculates the value of the specified column and , If the specified column type is not a numeric type , So the result is 0 |
max() | Calculate the maximum value of the specified column , If the specified column is of string type , So use string sort operation |
min() | Calculate the minimum value of the specified column , If the specified column is of string type , So use string sort operation |
avg() | Calculate the average value of the specified column , If the specified column type is not a numeric type , So the result is 0 |
Aggregate function pairs NULL value To deal with
- 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 value Number of records .
- sum and avg Function pair null value To deal with , These two functions ignore null value The existence of , It's like this record doesn't exist .
- max and min The function also ignores null Existence of value .
5、 Group query group by
Group query refers to the use of group by Group subqueries with words .
Format :
select Field 1, Field 2 ... from Table name group by Grouping field having Grouping conditions ;
Example :
-- Count the number of commodities in each category
select category_id, count(*) from product group by category_id;
After grouping , be select After Clause , Only grouped fields and aggregate statistical functions can appear , Other fields cannot appear .
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 the grouping results
Format :
select Field 1, Field 2... from Table name group by Grouping field having Grouping conditions ;
operation :
-- Count the number of commodities in each category , And only show the number greater than 1 Information about
select category_id, count(*) from product group by category_id having count(*) > 1;
-- Count the number of commodity categories , Total number of articles , Total sum , And add having Filter multiple criteria , The sum of total classified amounts is greater than 30
select category_id, count(*), sum(price) from product group by category_id having count(*) >1 and sum(price) > 30;
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-XqCaWYNJ-1644551252846)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220109182824134.png)]
6、 Paging query limit
Format
-- The way 1, Before display n strip
select Field 1, Field 2 ... from Table name limit n
-- The way 2 Pagination display
select Field 1, Field 2 ... from Table name 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
Example :
-- Before query 5 Bar record
select * from product limit 5;
-- From 5 Bar start , Show 5 strip
select * from product limit 5,5;
7、INSERT INTO SELECT sentence
Import data from one table into another table , The target table must exist
Format :
insert into table2(field1, field2, ...) select value1, value2, ... from table1;
perhaps
insert into table2 select * from table1;
Example :
-- Create a product2 surface , Will table 1 Insert the product name and price into product2 surface
CREATE TABLE PRODUCT2(
pname varchar(20),
price double
);
insert into product2 (pname, price) select pname, price from product;
Example 2:
-- Create a product3 surface , Statistics of commodity classification and quantity
CREATE table product3(
category_id varchar(20),
product_count int
);
insert into product3 select category_id, count(*) from product group by category_id;
边栏推荐
- Yolov5 target detection neural network -- calculation principle of loss function
- Seven polymorphisms
- 查看rancher中debug端口信息,并做IDEA Remote Jvm Debug
- Network five whip
- Mmclassification training custom data
- Yolov 5 Target Detection Neural Network - Loss Function Calculation Principle
- 无线WIFI学习型8路发射遥控模块
- Pytorch MLP
- Matlab imoverlay function (burn binary mask into two-dimensional image)
- 图像超分实验:SRCNN/FSRCNN
猜你喜欢
What is digital existence? Digital transformation starts with digital existence
Pytorch MLP
[loss functions of L1, L2 and smooth L1]
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
嵌入式软件架构设计-消息交互
【使用TensorRT通过ONNX部署Pytorch项目】
Riddle 1
Simply solve the problem that the node in the redis cluster cannot read data (error) moved
【上采样方式-OpenCV插值】
Pytorch softmax regression
随机推荐
Error modulenotfounderror: no module named 'cv2 aruco‘
Take you two minutes to quickly master the route and navigation of flutter
abap查表程序
Network five whip
Principle of persistence mechanism of redis
一款新型的智能家居WiFi选择方案——SimpleWiFi在无线智能家居中的应用
Four operations and derivative operations of MATLAB polynomials
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
Simply solve the problem that the node in the redis cluster cannot read data (error) moved
[yolov5.yaml parsing]
Liunx prohibit Ping explain the different usage of traceroute
【ijkplayer】when i compile file “compile-ffmpeg.sh“ ,it show error “No such file or directory“.
强化学习-学习笔记3 | 策略学习
Hash tag usage in redis cluster
[yolov3 loss function]
【Win11 多用户同时登录远程桌面配置方法】
HiEngine:可媲美本地的云原生内存数据库引擎
谜语1
Matlab superpixels function (2D super pixel over segmentation of image)
Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter