DAY 62 Advanced statements of mysql

table join query

Three kinds of connection in MYSQL database:

  • Inner join (inner join): Only return rows with equal join fields in the two tables (with intersection values)
  • left join (left join): Returns all records including all records in the left table and records with the same join field in the right table
  • right join (right join): Returns all records including all records in the right table and records with the same join field in the left table

Note: Oracle database supports outer join (outer join), mysql does not support

 

left join (left join)

left join (left join): Returns all records including all records in the left table and records with the same join field in the right table

 select * from location A LEFT JOIN store_info B on A.store_name=B.store_name;   #左连接

 right join (right join)

right join (right join): Returns all records including all records in the right table and records with equal join fields in the left table.

 select * from location A RIGHT JOIN store_info B on A.store_name=B.store_name;  #右连接

 inner join (inner connection)

Inner join (inner join): returns only rows with equal join fields in the two tables

方法一:
 select * from location A inner join store_info B on A.store_name=B.store_name;
 ​
 方法二:
 select * from location A, store_info B where A.store_name=B.store_name;
 ​
 方法三:
 select * from location A inner join store_info B using(store_name); #using()是函数,必须保证括号内的字段在两个表中是同名的


 Example:

Set the alias of the location table to A and the alias of the store_info table to B, query the rows with the same store_name field value in table A and table B, then group and summarize the region field, and calculate the sum of sales in the group

select A.region region,sum(B.sales) sales from location A,store_info B where A.store_name=B.store_name group by region;


view 

Views: Can be thought of as virtual tables or stored queries.

  • The difference between a view and a table is that the table actually stores data records, while the view is a structure built on the table, and it does not actually store data records.
  • Temporary tables disappear automatically after the user logs out or the connection to the database is disconnected, but the view does not disappear.
  • A view does not contain data, only its definition is stored, and its use generally simplifies complex queries. For example, if you want to perform join queries on several tables, and also perform statistical sorting operations, it will be very troublesome to write SQL statements. Using a view to join several tables, and then performing query operations on this view is the same as performing operations on a table. It's the same as querying, very convenient

grammar:

 CREATE VIEW "视图表名" AS "SELECT 语句";   #创建视图表
 ​
 DROP VIEW "视图表名";                     #删除视图表

Example:

The view table is the query result of the select statement, which can be understood as an alias of the select statement.

After the original table data changes, the result of the view table will also change

 #将两个表的连接查询,创建为视图表
 create view v_region_sales as select A.region region,sum(B.sales) sales from location A inner join store_info B on A.store_name=B.store_name group by region;
 ​
 select * from v_region_sales;     #查看视图表的存储结果
 ​
 drop view v_region_sales;         #删除视图表

 

 View table compared to derived table

In the derived table, two select queries are written in one sentence, which is more complicated and lengthy.

View tables, simplifying complex queries. You only need to create it once, and you can directly operate on the created view table later

 #派生表:C就是子查询中select语句的派生表。
 select sum(C.sales) from (select A.region region,sum(B.sales) sales from location A,store_info B where A.store_name=B.store_name group by region) C;
 ​
 ​
 #视图表:只需创建一次,后面可以直接对已创建好的视图表进行操作。
 create view v_region_sales as select A.region region,sum(B.sales) sales from location A inner join store_info B on A.store_name=B.store_name group by region;
 ​
 select sum(sales) from v_region_sales;    #对视图表进行操作

Whether the view table can insert data

  • If the view table is a join query of two tables, data cannot be inserted. Because the table structure is inconsistent with the original table.
  • If the structure of the view table is consistent with that of the original table, data can be modified and inserted.

    • For example, the original table has 3 fields, and the view table has 2 fields. As long as these 2 fields are consistent with the structure of the original table, data can also be modified and inserted. (as long as the view table is the result of a query on a single table)

Example 1

If the view table is a join query of two tables, data cannot be inserted. Because the table structure is inconsistent with the original table

#该视图表是两个表的连接查询
 create view v_region_sales as select A.region region,sum(B.sales) sales from location A inner join store_info B on A.store_name=B.store_name group by region;
 ​
 #查看视图表结构,和原表不一致。
 desc v_region_sales;
 ​
 #插入数据失败
 insert into v_region_sales values('middle',500);


Example 2:

If the structure of the view table is consistent with that of the original table, data can be modified and inserted. (as long as the view table is the result of a query on a single table)

#该视图表只是对单个表的查询结果。
 create view v_test_info as select * from store_info;
 ​
 #查看视图表结构,和原表一致。
 desc v_test_info;
 ​
 #插入数据成功
 insert into v_test_info values('NYC',500,'2020-12-10');



Union

UNION: combine the results of two SQL statements, and the fields generated by the two SQL statements must be of the same data record type

UNION (deduplication after merging)

The resulting data record values ​​will not be duplicated and will be sorted according to the order of the fields. # Deduplication after merging

 [select 语句1] UNION [select 语句2];
 ​
 示例:
 select store_name from location union select store_name from store_info;
 #将两个表的store_name字段的值合并起来,union生成的结果去重

 intersection value

Intersection value: take the intersection of the results of two SQL statements

Use union all + group by+having to find the intersection value

Note: When using the union method to find the intersection, the target field values ​​​​of the two tables must be deduplicated first, and then merged. Avoid miscalculations due to duplicate values ​​in a single table

 #两个表各自将store_name字段的值进行去重,之后合并,再创建视图表。
 create view v_store_name as select distinct store_name from location union all select distinct store_name from store_info;
 ​
 #对视图表的store_name字段进行分组汇总,计算每组的数量。
 select store_name,count(*) from v_store_name group by store_name;
 ​
 #对视图表的store_name字段进行分组汇总,计算每组的数量,过滤出数量大于1的store_name字段值,就是两个表的交集部分。
 select store_name from v_store_name group by store_name having count(*) >1;

  Intersect Set Values ​​Using Inner Join

 ​ select A.store_name from location A inner join store_info B using(store_name);

Take the intersection of the store_name field values ​​of the two tables

 select A.store_name from location A inner join store_info B on A.store_name=B.store_name;
 ​
 select A.store_name from location A inner join store_info B using(store_name);

 Take the intersection of the store_name field values ​​of the two tables, then remove the duplicates and add distinct

 select distinct A.store_name from location A inner join store_info B using(store_name);
 #使用左连接查询store_name字段的交集部分
 select * from location A left join store_info B using(store_name);
 ​
 #使用左连接查出store_name字段的交集值,之后去重
 select distinct A.store_name from location A left join store_info B using(store_name) where B.store_name is not null;

 Intersect values ​​using right join

#使用右连接查出store_name字段的交集值,之后去重
 select distinct A.store_name from location A right join store_info B using(store_name) where A.store_name is not null;
 ​
 #方法二:
 select distinct A.store_name from location A right join store_info B on A.store_name=B.store_name where A.store_name is not null;


 Use subquery to find the intersection value in


 #使用子查询的方式查出store_name字段的交集值,之后去重
 select distinct store_name from location where store_name in (select store_name from store_info);

 no intersection value

No intersection value: Display the result of the first SQL statement that has no intersection with the result of the second SQL statement, and there is no duplication.

Use union all + group by+having to find no intersection value

 #两个表各自将store_name字段的值进行去重,之后合并,再创建视图表。
 create view v_store_name as select distinct store_name from location union all select distinct store_name from store_info;
 ​
 #对视图表的store_name字段进行分组汇总,计算每组的数量。
 select store_name,count(*) from v_store_name group by store_name;
 ​
 #对视图表的store_name字段进行分组汇总,计算每组的数量,过滤出数量等于1的store_name字段值,就是两个表无交集的部分。
 select store_name from v_store_name group by store_name having count(*) =1;

CASE

case: is a keyword used by SQL as logic such as IF-THEN-ELSE

grammar:

SELECT CASE ("字段 名")
     WHEN "条件1" THEN "结果1"
     WHEN "条件2" THEN "结果2"
     [ELSE "结果N"]
     END
 FROM "表名";
     
 # "条件"可以是一个数值或是公式。ELSE子句则并不是必须的。


Example:

 select store_name,CASE store_name        #对sttore_name字段值进行判断
     WHEN 'Los Angeles' THEN sales * 2    #当店名为洛杉矶时销售额乘2
     WHEN 'Boston' THEN 2000              #当店名为波士顿时销售额显示2000
     ELSE sales / 2                       #其他店名则销售额除以2
     END                                  #判断结束
 "new sales", date                        #用于显示的字段名
 from store_info;
 ​
 #"new sales" 是用于case那个字段的字段名。
 ​
 #注:查询并不改变原表的值。

 The difference between NULL (NULL) and no value (' ') The difference between NULL (NULL) and no value (' '):

  1. The length of no value is 0, which does not take up space; while the length of NULL value is NULL, which takes up space
  2. IS NULLOr IS NOT NULL, it is used to judge whether the field is NULL or not NULL, and it cannot find out whether it has no value
  3. Valueless judgments are handled using =' 'or < >' '. <> represents not equal to
  4. When counting the number of rows through  count ()the specified field, if a NULL value is encountered, it will be automatically ignored, and if no value is encountered, it will be added to the record for calculation

Regular Expressions - Exact Query

match pattern describe example
^ start character of matching text '^bd' matches a string starting with bd
$ Matches the end character of the text 'qn$' matches strings ending with qn
. matches any single character 'st' matches any string with one character between s and t
* matches zero or more of the characters preceding it 'fo*t' matches t preceded by any o
+ Matches the preceding character 1 or more times 'hom+' matches a string starting with ho followed by at least one m
string matches the specified string 'clo' matches strings containing clo
p1lp2 matches p1 or p2 'bglfg' matches bg or fg
[...] Matches any character in the character set '[abc]' matches a or b or c
[^...] matches any character not in parentheses '[^ab]' matches a string that does not contain a or b
{n} Match the preceding string n times 'g{2}' matches a string containing 2 g
{n,m} Matches the preceding string at least n and at most m times 'f{1,3}' matches f at least 1 time and at most 3 times

grammar:

 select "字段" from "表名" where "字段" regexp {模式};

Example:

#查询store_name字段包含字符串"os"的行
 select * from store_info where store_name regexp 'os';
 ​
 #查询store_name字段以A-G开头的行
 select * from store_info where store_name regexp '^[A-G]';
 ​
 #包含Ho或者Bo
 select * from store_info where store_name regexp 'Ho|Bo'; 
 ​
 #以字符串“on”为结尾
 select * from store_info where store_name regexp 'on$';
 ​
 #以“Bo”开头且以“on”为结尾
 select * from store_info where store_name regexp '^Bo.*on$';
 ​
 #查询所有QQ邮箱
 select * from store_info where store_name regexp '.*@qq.com$';`


 

Guess you like

Origin blog.csdn.net/weixin_57560240/article/details/130794905