当前位置:网站首页>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;
边栏推荐
- Video networkstate property
- Ncp1342 chip substitute pn8213 65W gallium nitride charger scheme
- 【TFLite, ONNX, CoreML, TensorRT Export】
- yolov5目标检测神经网络——损失函数计算原理
- Mmclassification training custom data
- Hiengine: comparable to the local cloud native memory database engine
- 【yolov5.yaml解析】
- vscode快捷键
- Pytorch linear regression
- Seven polymorphisms
猜你喜欢
A guide to threaded and asynchronous UI development in the "quick start fluent Development Series tutorials"
Understand kotlin from the perspective of an architect
July Huaqing learning-1
【 YOLOv3中Loss部分计算】
强化学习-学习笔记3 | 策略学习
Redis master-slave mode
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
Troubleshooting of high memory usage of redis in a production environment
互联网公司实习岗位选择与简易版职业发展规划
[yolov3 loss function]
随机推荐
Is investment and finance suitable for girls? What financial products can girls buy?
Sentinel sentinel mechanism of master automatic election in redis master-slave
liunx禁ping 详解traceroute的不同用法
[mainstream nivida graphics card deep learning / reinforcement learning /ai computing power summary]
Simple production of wechat applet cloud development authorization login
Understand kotlin from the perspective of an architect
16 channel water lamp experiment based on Proteus (assembly language)
Thoughts and suggestions on the construction of intelligent management and control system platform for safe production in petrochemical enterprises
强化学习-学习笔记3 | 策略学习
How to clear floating?
1个插件搞定网页中的广告
Network five whip
Course design of compilation principle --- formula calculator (a simple calculator with interface developed based on QT)
[cloud native | kubernetes] actual battle of ingress case (13)
Understanding the architecture type of mobile CPU
Want to ask, how to choose a securities firm? Is it safe to open an account online?
The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)
HiEngine:可媲美本地的云原生内存数据库引擎
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
【SingleShotMultiBoxDetector(SSD,单步多框目标检测)】