MYSQL basic operation - select query statement [continued]


foreword

内容:MYSQL基本操作-select 查询语句【续】

aggregate function

maximum value (max)

select max(bookprice) as '最贵的书' from book;

Minimum value (min)

select min(borrowsum) as '最受嫌弃的书...' from book;

Quantity (count)

select count(bookid) from book;

sum

select sum(borrowsum) from book;

average value (avg)

select avg(bookprice) from book;

Group query

  • The group by keyword can group query results according to one or more fields
  • group by is generally used in combination with Mysql aggregate functions
  • If you need to specify conditions to filter the grouped result set, you need to combine the having keyword; reason: where cannot be used in conjunction with aggregate functions and where is executed before group by
 GROUP BY  <字段名>[,<字段名>,<字段名>]

simple grouping

select borrowsum, count(bookid) from book group by borrowsum;

Filter the grouping results
having keywords to filter the data grouped by group
by having all operators and syntaxes that support where

select borrowsum, count(bookid) from book group by borrowsum having count(bookid) = 1;

group sort

select borrowsum, count(bookid) from book group by borrowsum order by count(bookid) desc;

Statistical function group query

select 
	borrowsum,group_concat(bookname) 
from book 
group by borrowsum 
order by borrowsum desc;

– group_concat connects the values ​​in the same group generated by group by to return a string result, and displays the values ​​in each group after grouping. Multiple group
query, table
creation statement and insert data

-- ----------------------------
-- Table structure for choose_course
-- ----------------------------
DROP TABLE IF EXISTS `choose_course`;
CREATE TABLE `choose_course` (
  `course_name` char(10) DEFAULT NULL,
  `semester_number` int(11) DEFAULT NULL,
  `student_name` char(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of choose_course

INSERT INTO `choose_course` VALUES ('语文', '1', '李雷');
INSERT INTO `choose_course` VALUES ('语文', '1', '韩梅梅');
INSERT INTO `choose_course` VALUES ('语文', '1', '露西');
INSERT INTO `choose_course` VALUES ('语文', '2', '莉莉');
INSERT INTO `choose_course` VALUES ('语文', '2', '格林');
INSERT INTO `choose_course` VALUES ('数学', '1', '李雷');
INSERT INTO `choose_course` VALUES ('数学', '1', '名字真难起...');
SELECT
	course_name,
	semester_number,
	count('hello')
FROM
	choose_course
GROUP BY
	course_name,
	semester_number;
  • When multiple fields are grouped and queried, group by the first field first, if the first field has the same value, then group the grouped results by the second field, and so on
  • If each value of the first field is unique, it will not be grouped by the second field

The group by clause is also used in conjunction with the where conditional statement. When combined, where comes first and group by follows. That is, first use where to filter the record set of select xx from xx, and then use group by to group the filtered results and use the having clause to filter the grouped results. It is necessary to pay attention to the difference between the usage of having and where
:

  • Having can only be used after group by to filter the grouped results (that is, the prerequisite for using having is grouping).

  • where must be before group by

  • Aggregate functions are not allowed in the conditional expression after where, but having is allowed.
    When where, group by, having, and order by appear in a query statement at the same time, the execution order and writing order are:

  • Execute where xx to filter the data in the entire table and return the first result set.

  • Use group by grouping for the first result set and return the second result set.

  • Execute select xx for each set of data in the second result set, execute several times for as many sets as there are, and return the third result set.

  • Execute having xx for the third set to filter and return the fourth result set.

  • Sort for the fourth result set.
    Multi-table query
    The difference between multi-table query

  • cross join: cross connection

  • inner join: inner connection

  • left join: left outer connection

  • right join: right outer join

  • union, union all: full connection

insert image description here

inner join

Example table: book
insert image description here

Example table: readertype

retypeid typename borrowquantity borrowday
1 students 10 30
2 teachers 20 60
3 administrators 15 30
4 staff 15 20
use the from clause
SELECT * FROM book, reader;
– combine the two tables into one return
select book.bookid,book.bookname ,reader.readerid,reader.readername from book,reader;
– Combine and return the specified fields of the two tables
Specify the connection condition in where
SELECT * FROM readertype, reader
WHERE reader.retypeid = readertype.retypeid;
use the join keyword to connect— Use inner join
SELECT <field name> FROM <table 1> INNER JOIN <table 2> [ON clause]
– inner join uses on to set the conditional expression. If on is not added, inner join and cross join are the same
– cross join ... on and inner join ... on actually have the same effect (but in standard sql, cross join does not support on, only Mysql supports it)
– inner join can connect ≥ two tables
– inner join can also use where to specify the connection condition, but inner join … on is the official standard writing method, and where may affect query performance
– inner join can also only write join without adding inner

select * from readertype join reader on reader.retypeid = readertype.retypeid;
select * from readertype inner join reader on reader.retypeid = readertype.retypeid;

Use an alias for the data table

select readertype.retypeid,readertype.borrowquantity,reader.readerstatus
from readertype join reader on reader.retypeid = readertype.retypeid;
select a.retypeid,a.borrowquantity,b.readerstatus 
from readertype as a join reader as b on b.retypeid = a.retypeid;

outer join

Example table: user

user_id user_name user_sex
1 Zhang San 1
2 Li Si 1
3 Wang Wu 1 4 Zhao Liu 1
5
Qian Qi 1
6 Sun Ba 1
7 Zhou Lao Jiu 1
8 Wu Lao Shi 1
Example table: user_detail

user_detail_id user_detail_address user_detail_phone user_detail_uid
1 河南平顶山15639279531 1
2 河南平顶山15639279532 2
3 河南平顶山15639279533 3
4 河南平顶山15639279534 4
11 河南平顶山15639279521 11
12 河南平顶山15639279522 12
13 河南平顶山15639279523 13
14 河南平顶山15639279524 14
外连接分为两种: left join, right join.
The outer join shows more content than the inner join. It is a supplement to the inner join. The
main table of the left join is the left table, and the slave table is
the right table. The right join is the main table and the slave table is the left table
The outer join will return all the data in the main table, regardless of whether there is matching data in the slave table. If there is no matching data in the slave table, it will default to a null value (NULL). The outer join only returns the matching data in the slave table. Key points
:
in When using an outer join, it is necessary to distinguish the results of the query whether to display all the records of the left table or all the records of the right table

SELECT <字段名> FROM <1> LEFT OUTER JOIN <2> <ON子句>
SELECT <字段名> FROM <1> RIGHT OUTER JOIN <2> <ON子句>

The outer can be omitted, just write left join, right join
on is to set the connection condition of the left join,
the chestnut of the left join cannot be omitted

select * from user left join user_detail on user.user_id = user_detail.user_detail_uid;

The retrieval result after the left join is to display all the data of the user and the data satisfying the where condition in user_detail.

right join chestnuts

select * from user right join user_detail on user.user_id = user_detail.user_detail_uid;
右连接后的检索结果是user_detail的所有数据和user中满足where 条件的数据。

Cross connection cross join
Cartesian product

Suppose, there are two sets A and B

A = {1,2}B = {3,4}
Cartesian product of set A and set B = set A * set B; that is, the two tables are multiplied as follows:

AxB = {(1,3),(1,4),(2,3),(2,4)}
In Mysql, the Cartesian product between tables is not recommended, it will generate a lot of unreasonable Data;
SELECT <field name> FROM <table 1> CROSS JOIN <table 2>
[WHERE] SELECT <field name> FROM <table 1>, <table 2> [WHERE clause] The
following two sentences have the same effect

select * from user cross join user_detail ;
select * from user,user_detail;

The following two sentences have the same effect

select * from user cross join user_detail on user_detail.user_detail_uid = user.user_id;
select * from user,user_detail where user.user_id = user_detail.user_detail_uid;

self-join

A table is assumed to be two identical tables, and the two tables (the same two tables) are joined to obtain a Cartesian product, and then the results in the Cartesian product are filtered according to where.
Self-join is a join operation of different instances of the same table.
Self-join must specify an alias (aliasName) to distinguish different instances.

SELECT	b2.bookname,b2.borrowsum 
FROM	book AS b2,book AS b1 
WHERE	b2.borrowsum > b1.borrowsum AND b1.bookname = '中医的故事' 
ORDER BY b2.borrowsum DESC,b2.bookname;
SELECT	b2.bookname,b2.borrowsum 
FROM book AS b2 join book AS b1 on b2.borrowsum > b1.borrowsum 	
where b1.bookname = '中医的故事' 
ORDER BY b2.borrowsum DESC,b2.bookname;

First copy two identical tables
and filter where on the first table to get the bookname equal to the borrowsum of the story of Chinese medicine.
Join table 1 and table 2 to get the borrowsum greater than the borrowsum of the story of Chinese medicine, and
then combine the bookname and the borrowsum in table 2 The borrowsum information is displayed
. Alias: The two tables in this query are actually the same table. The DBMS does not know which table you are referencing, so you need to use an alias to solve this problem.

joint query

In fact, Mysql does not have a full connection, Oracle only has a full connection (full join)
, but in MySQL, the union keyword can achieve the same effect, so here we also want to introduce union

[sql1]UNION [ALL | DISTINCT][sql2]UNION [ALL | DISTINCT][sql3]....

sql1, sql2, sql3: usually written query sql, you can connect many sql
ALL: optional parameter, return all result sets, including duplicate data
distinct: optional parameter, delete duplicate data in the result set (default only write union will also deduplication, so it's okay to not add)

select * from user left join user_detail on user.user_id = user_detail.user_detail_uid 
union 
select * from user right join user_detail on user.user_id = user_detail.user_detail_uid;

For multiple sqls connected by union, the field names of the result sets from each sql query should be consistent**[only the names need to be the same, the order can be different, but the recommendations are the same]**, you can see the following chestnut final
union The field order of the result set of the connection query will be based on the field order of the result set found in the first sql. Subquery Subquery
is
commonly used in our query method. Through subquery, multi-table query can be realized.
Subquery refers to: Nest a query statement in another query statement Subqueries
can be used in select, update, delete statements, and multi-level nesting
WHERE <expression> <operator> (subquery)
The operator can be a comparison Operators, in, not in, exists, not exists
not are of course negation
Use the subquery of the comparison operator to
query the book number, book name, book unit price, and price from high to low

SELECT	bookid,	bookname,bookprice
FROM	book 
WHERE	bookprice > ( SELECT bookprice FROM book WHERE bookname = '机械设计手册' ) 
ORDER BY bookprice DESC;
查询类别是学生的读者信息, 包括读者编号, 读者姓名, 发证日期
SELECT	readerid,readername,readerdate 
FROM	reader 
WHERE	retypeid = ( SELECT retypeid FROM readertype WHERE typename = '学生' );

You can also use linked tables to query...

SELECT	readerid,readername,readerdate 
FROM	reader	JOIN readertype ON readertype.retypeid = reader.retypeid 	AND typename = '学生';

In fact, the function of subqueries can also be completed through table joins (join)
. Generally speaking, table joins (inner joins, outer joins, etc.) can be queried with subqueries, but the reverse is not necessarily the case. Some subqueries cannot be used for table joins. To replace
the subquery is more flexible, suitable as a query filter condition
Table connection is more suitable for viewing the data set after the connection table
[not] in subquery
Query the book id, book name that has been lent

SELECT	bookid,	bookname 
FROM	book 
WHERE	bookid IN ( SELECT bookid FROM bookstorage WHERE bookstatus = '借出' );
查询没有借出(在馆)的书籍id, 书籍名称
SELECT	booki,	bookname 
FROM	book
WHERE	bookid NOT IN ( SELECT bookid FROM bookstorage WHERE bookstatus = '借出' );
SELECT	bookid,	bookname 
FROM	book 
WHERE	bookid IN ( SELECT bookid FROM bookstorage WHERE bookstatus != '借出' );
any 子查询

any greater than the smallest < any less than the largest = any is equivalent to in();

Select the book whose price is greater than the cheapest price of Machinery Industry Press in the book table (book ID, book name, publisher, price)

SELECT	booki,	bookname,bookpublisher,	bookprice 
FROM	book 
WHERE	bookprice > ANY ( SELECT bookprice FROM book WHERE bookpublisher = '机械工业出版社' );

all subquery

all greater than the largest

< all less than the smallest

Select the book whose price is greater than the most expensive price of Machinery Industry Press in the book table (book ID, book name, publisher, price)

SELECT	bookid,	bookname,bookpublisher,	bookprice 
FROM	book 
WHERE	bookprice > all ( SELECT bookprice FROM book WHERE bookpublisher = '机械工业出版社' );
[not] exists子查询

View the category id and category name of no books in the book category table

SELECT	typeid,	typename 
FROM	booktype 
WHERE	NOT EXISTS ( SELECT * FROM book WHERE booktype.typeid = book.typeid );

View the category id and category name of the book in the book category table

SELECT	typeid,	typename 
FROM	booktype 
WHERE	EXISTS ( SELECT * FROM book WHERE booktype.typeid = book.typeid );

A comparison between in and exists
in exists
returns TRUE when the expression is equal to a value in the result set returned by the subquery, otherwise it returns FALSE; it is used to determine whether the result set of the subquery is empty, if the result set of the subquery is not If it is empty, return TRUE, otherwise return FALSE;
it is suitable for the case where the outer table is large and the inner table is small, and it is suitable for the case where the inner table is large and the outer table is small.
No matter which table is large, using not exists is faster than not in
1. A is an expression, B It is the subquery result set 2. If A is in B, it returns True
Summary
Subquery statements can be nested in any expression in the sql statement

Fields, table names, and query conditions can all be nested with subqueries!

select <子查询> from <表名> where <查询条件>
select <字段> from <子查询> as <别名> where <查询条件>
select <字段> from <表名> where <子查询>

common mistakes

select * from (select * from emp);
this will report an error, because no alias is specified for the subquery

correct spelling

select * from (select * from emp) as t;

If <table name> nests a subquery, you must specify an alias for the table. Generally, a result set with multiple rows and columns will be returned as a new temporary table.

Tables that appear only in the subquery but not in the parent query cannot be included in the output columns

The final result set of multi-layer nested subquery only contains the fields that appear in the select statement of the parent query (the outermost query). The result set
of the subquery is usually used as the data source of its outer query or used for conditional judgment

Guess you like

Origin blog.csdn.net/m0_51607907/article/details/127128868