1. Five sub-sentences of mysql query
where (conditional query), having (filtering), group by (grouping), order by (sorting), limit (limiting the number of results)
1. Where common operators:
comparison operator
> , < , = , != (< >) , >= , <=
in(v1,v2...vn)
between v1 and v2 between v1 and v2 (including v1, v2)
Logical Operators
not ( ! ) logical negation
or ( || ) logical or
and ( && ) logical AND
where price>=3000 and price <= 5000 or price >=500 and price <=1000
Take a value of 500-1000 or 3000-5000
where price not between 3000 and 5000
A value not between 3000 and 5000
fuzzy query
like
Wildcard:
% any character
_ single character
where goods_name like 'Nokia%'
where goods_name like 'Nokia N__'
2. group by grouping
In general, group only makes sense if it is used together with statistical functions (aggregate functions).
如:select goods_id,goods_name,cat_id, max(shop_price) from goods group by cat_id;
The good_name in the result taken here is wrong! Because shop_price uses the max function, then it is the largest, and the group by grouping is used in the statement, then the goods_name does not use the aggregation function, it is only the first product under cat_id, and will not be changed because shop_price changes
Five statistical functions in mysql:
(1) max: find the maximum value
#This will take out the value of the largest price, only the value
select max(goods_price) from goods
#Query the highest price under each column
select cat_id,max(goods_price) from goos group by cat_id;
#Find the item number with the highest price
select goods_id,max(goods_price) from goods group by goods_id;
(2) min: find the minimum value
(3) sum: find the sum of the total
#Seek the sum of the product inventory
select sum(goods_number) from goods;
(4) avg: average value
# Find the average price of each item
select cat_id,avg(goods_price) from goods group by cat_id;
(5) count: find the total number of rows
#Seek the type of goods under each column
select cat_id, count(*) from goods group by cat_id;
###
To understand each field name as a variable, it can perform operations
###
Example: Query how much the price of each commodity in our store is lower than the market price;
select goods_id,goods_name,goods_price-market_price from goods;
Query the payment for goods under each column
select cat_id,sum(goods_price*goods_number) from goods group by cat_id;
###You can use as to take an alias for the calculation result###
select cat_id,sum(goods_price * goods_number) as hk from goods group by cat_id
Not only column names can take aliases, but table names can also take aliases
3. Similarities and differences between having and where
Having is similar to where, you can filter data, how to write the expression after where, and how to write after having
where works
on
the columns in the table ,
querying
the data
having
plays a role in the columns in the query results and
filters
the data
#Query how much the product price in our store is lower than the market price, and output products with a lower price of more than 200 yuan
select goods_id,good_name,market_price - shop_price as s from goods having s>200 ;
//You can't use where because s is the query result, and where can only filter the field names in the table
If you use where it is:
select goods_id,goods_name from goods where market_price - shop_price > 200;
#Use where and having at the same time
select cat_id,goods_name,market_price - shop_price as s from goods where cat_id = 3 having s > 200;
#Query the columns with the backlog of goods exceeding 20,000 yuan, and the backlog of goods in this column
select cat_id,sum(shop_price * goods_number) as t from goods group by cat_id having s > 20000
#Query the average score of students who failed two or more subjects
Ideas:
# first calculate the average score of all students
select name,avg(score) as pj from stu group by name;
#Find out the failures of all students
select name,score<60 from stu;
#here score<60 is a judgment statement, so the result is true or false, true is 1 in mysql, false is 0
#Find out students who fail two or more subjects
select name,sum(score<60) as gk from stu group by name having gk > 1;
#Comprehensive results
select name,sum(score<60) as gk,avg(score) as pj from stu group by name having gk >1;
4、order by
(1) order by price //default ascending order
(2) order by price desc //sort in descending order
(3) order by price asc //Ascending order, the same as the default
(4) order by rand() //Random arrangement, inefficient
# Arrange by column number in ascending order, and the commodity prices under each column are arranged in descending order
select * from goods where cat_id !=2 order by cat_id,price desc;
5、limit
limit [offset,] N
offset offset, optional, if not written, it is equivalent to limit 0,N
N take out the entry
#Take the commodity with the 4th-6th highest price
select good_id,goods_name,goods_price from goods order by good_price desc limit 3,3;
###Query the most expensive item under each column
Ideas:
#First sort the commodity prices under each column
select cat_id,goods_id,goods_name,shop_price from goods order by cat_id,shop_price desc;
#The commodity in the first row of each column in the above query results is the most expensive commodity
#Understand the above query result as a temporary table [existing in memory] [subquery]
# Then select the most expensive product in each column from the temporary table
select * from (select goods_id,goods_name,cat_id,shop_price from goods order by cat_id,shop_price desc) as t group by cat_id;
#group by cat_id is used here because the first item of each column in the temporary table is the most expensive item, and the aggregation function is not used before group by, so the first row of data of each group is taken by default, here cat_id grouping
A good understanding of the model:
1. The expression after where, put the expression in each line to see if it holds
2. Fields (columns), understood as variables, can be operated (arithmetic operations and logical operations)
3. The result of taking out can be understood as a temporary table
Second, mysql sub query
1. Where type subquery
(Take the inner query result as the comparison condition of the outer query)
#Do not order by to check the latest products
select goods_id,goods_name from goods where goods_id = (select max(goods_id) from goods);
#Take out the latest products under each column (goods_id is unique)
select cat_id,goods_id,goods_name from goods where goods_id in(select max(goods_id) from goods group by cat_id);
2. From subquery
(The query results of the inner layer are available for the outer layer to query again)
#Use subquery to find out the average grades of students who have failed two or more subjects
Ideas:
#First find out which students have failed more than two subjects
select name,count(*) as gk from stu where score < 60 group by name having gk >=2;
#For the above query results, we only need the name, so take the name again
select name from (select name,count(*) as gk from stu group by name having gk >=2) as t;
#Find these students, then calculate their average score
select name,avg(score) from stu where name in (select name from (select name,count(*) as gk from stu group by name having gk >=2) as t) group by name;
3. exists subquery
(Get the outer query results to the inner layer to see if the inner query is valid)
#Query which columns have commodities, column table category, commodity table goods
select cat_id,cat_name from category where exists(select * from goods where goods.cat_id = category.cat_id);
Third, the usage of union
(Combining the results of two or more queries requires the same number of columns to be queried. It is recommended that the corresponding column types of the query be the same. Multiple tables can be queried. If the column names are different when querying statements multiple times, the first One-time column name! If the values of each column of the rows taken out in different statements are the same, the result will be automatically de-duplicated. If you do not want to de-duplicate, you need to add all to declare, that is, union all)
## The existing table a is as follows
id num
a 5
b 10
c 15
d 10
Table b is as follows
id num
b 5
c 10
d 20
e 99
Find the sum of the same id in two tables
select id,sum(num) from (select * from ta
union
select * from tb) as tmp group by id;
//The above query results can indeed output the results correctly in this example, but if the value of b in tb is changed to 10, the value of b in the query result is 10, because b in ta is also 10, so after union Will be filtered out a duplicate result, then use union all
select id,sum(num) from (select * from ta
union all
select * from tb) as tmp group by id;
# Take the commodities in the 4th and 5th columns, arrange them in ascending order, and arrange the commodity prices in each column in descending order, complete with union
select goods_id,goods_name,cat_id,shop_price from goods where cat_id=4 union select goods_id,goods_name,cat_id,shop_price from goods where cat_id=5 order by cat_id,shop_price desc;
[If there is order by in the clause, it needs to be wrapped with ( ), but it is recommended to use order by at the end, that is, to sort the final merged result]
# Take the 3rd and 4th columns, the top 3 products with the highest price in each column, and the results are sorted in descending order by price
(select goods_id,goods_name,cat_id,shop_price from goods where cat_id=3 order by shop_price desc limit 3) union (select goods_id,goods_name,cat_id,shop_price from goods where cat_id=4 order by shop_price desc limit 3) order by shop_price desc;
Fourth, left join, right join, inner join
Existing table a has 10 data, table b has 8 data, then what is the Cartesian product of table a and table b?
select * from ta,tb //The output result is 8*10=80
1. Left join
Take the left table as the criterion, go to the right table to find the data, if there is no matching data, fill the blank with null, so the number of output results >= the original data number of the left table
Syntax: select n1,n2,n3 from ta
left join
tb
on
ta.n1= ta.n2 [
The expression after on here is not necessarily =, it can also be >, < and other arithmetic and logical operators] [After the connection is completed , it can be treated as a new table, using where and other queries
]
#Take out the five products with the highest price and display the category name of the product
select goods_id,goods_name,goods.cat_id,cat_name,shop_price from goods left join category on goods.cat_id = category.cat_id order by shop_price desc limit 5;
2. Right join
a left join b 等价于 b right join a
It is recommended to use left join instead of right join
语法:select n1,n2,n3 from ta
right join
tb
on
ta.n1= ta.n2
3. Inner connection
The query result is the
intersection
, [that is, the union of the results of the left and right joins after removing the null items (removing duplicates)]
mysql does not currently support outer joins (that is, the union of left and right join results, without removing null items)
语法:select n1,n2,n3 from ta
inner join
tb
on
ta.n1= ta.n2
#########
Example: Existing table a
name hot
a 12
b 10
c 15
Table b:
name hot
d 12
e 10
f 10
g 8
Table a left joins table b to query hot same data
select a.*,b.* from a
left join
b on a.hot = b.hot
search result:
name hot name hot
a 12 d 12
b 10 e 10
b 10 f 10
c 15 null null
As can be seen from the above, the columns of the query result table a all exist, and the data of table b only displays the items that meet the conditions
Another example is table b left join table a, query hot same data
select a.*,b.* from b
left join
a on a.hot = b.hot
The query result is:
name hot name hot
d 12 a 12
e 10 b 10
f 10 b 10
g 8 null null
Another example is that table a right joins table b to query the same data as hot
select a.*,b.* from a
right join
b on a.hot = b.hot
The query result is the same as the above b left join a
###Exercise, query the name of the product, the category it belongs to, the brand it belongs to
select goods_id,goods_name,goods.cat_id,goods.brand_id,category.cat_name,brand.brand_name from goods left join category on goods.cat_id = category.cat_id left join brand on goods.brand_id = brand.brand_id limit 5;
Understanding: The result after each connection can be seen as a new table