Database------DQL operation

DQL

Data query language, mainly used to query data, the command used is select

Common query methods

  • SimpleQuery
  1. simple query
  2. table based query
  3. conditional query
  4. Group query
  5. Group filter query
  6. to sort
  7. paging
  • SubQuery (subquery)
  1. Column-based subqueries
  2. conditional subquery
  • nested query
  • Association query
  • collection query
  • with query

SimpleQuery

  • simple query
select 1 ;

-- 查询当前系统时间 
select now();

-- 查询数据库的版本
select version();

-- 查询当前登录用户信息
select user();

pS: It can mainly be used for heartbeat detection between database clusters

  • table based query
select column... from <tableName> ;

Query column ... Multiple columns are separated by commas
If you want to query all fields, you can use *to replace all the columns in the query, but in actual development, it is not recommended to use*

  • condition based query
    1. Relationship condition query
    2. logical query
    3. range query
    4. enum query
    5. NULL query
    6. fuzzy query
select column ... from <tableName> where 条件 ;
  • aggregate function

    • count() : statistics,
    • max() : Find the maximum value
    • min() : Find the minimum value
    • sum() : sum
    • avg() : average value
-- 查询 学生表中的 学生个数 

-- 会将每一行当作一条记录进行统计
select count(*) from tb_student; 
-- 如果按照字段统计 、那么字段的值如果是空,则不参与统计
select count(id) from tb_student ;
-- 
select count(1) from tb_student ;

When the counted field is the primary key, the execution efficiency is: count(id) > count(1) > count( ) When
the counted field is an ordinary field, the execution efficiency is: count(1) > count(column) > count ("
")
Aggregate function does not count null values

  • Group query group by
-- 查询 学生中, 各个系 有多少人 

select tie_id , count(id) from tb_student group by tie_id ;

Grouping has requirements for query columns a) query columns appear in aggregate functions, b) query columns appear after group by
If aggregate functions and ordinary columns appear in query columns, then the SQL should use grouping

  • Group filter query having
-- 根据年龄分组 、并查询 组成员数 > 3 的 组
select * from tb_student group by age having count(1)>3 ;
-- 查询 班级中 相同名字的 学生名 
select name from tb_student group by name having count(1)>1 ;

Having must be used after grouping, and where is to filter all the data in the table. In terms of execution efficiency, where is higher than having. In terms of
execution order, where is executed first than having. Can use where to filter data try not to use having to filter

  • sort order by
    • asc : sort in ascending order
    • desc : sort in descending order
-- 查看所有的语文成绩、并按照成绩降序排列
select * from tb_score where score = '语文' order by score desc ;
  • Pagination query limit
select * from tb_score limit [<offset>, ] <rows> ;

offset: offset, starting from 0 by default, if there is no offset, the default is 0
rows: used to set the number of rows displayed on each page page
: represents the page number pages
: represents the total number of pages
total: represents the total number of rows

offset = (page - 1) * rows ;

pages = (total -1 )/rows + 1 ;

Full command for simple query

select column... from <tableName> 

where 条件 

group by 分组字段列表 

having  筛选条件 

order by 排序字段列表 

limit [<offset> ,] <rows>

SubQuery

Subquery can better query the desired data, it is a special kind of nested query

  • Column-based subqueries
  • conditional subquery

Column-based subqueries

In the query column, contains a query statement

-- 查询 ID = 1000 的 学生名、系ID、系名
select t.id , 
		  t.name , 
		  t.tie_id, 
	      (select x.name from tb_tie x where x.id = t.tie_id) as xname
from tb_student t where t.id = 1000;

The result of the subquery must be a single column, single value

conditional subquery

In the query condition, contains a query statement

  • relational conditional subquery
-- 查询 语文最高成绩对应的学号 

select stu_id from tb_score t where score = 
  (select max(score) from tb_score s where s.subject =  t.subject)
and subject = '语文'; 

-- 查询 成绩 超过 语文的平均成绩的 学号 
select s.stu_id from tb_score s where 
s.score > (select avg(x.score) from tb_score x where x.subject = '语文')

A relational conditional subquery requires that the subquery return a single column with a single value

  • in conditional subquery
-- 查询 每一个科目的最高成绩对应的学生信息 

select * from tb_student where id in 
(
	select stu_id from tb_score f 
		where  score = (select  max(score) from tb_score x where x.subject = f.subject) 
);

The in conditional subquery is required to return a single column with multiple values

  • exists conditional subquery
select * from tb_student t where exists 
(
	  select 1 from tb_score f 
		where f.score =  (select max(score) from tb_score x where x.subject = f.subject)
		and f.stu_id = t.id 
);

If the exists subquery has a result, it means it exists, otherwise it means it does not exist

nested query

Treat the result of a query as a table to continue querying


select b.* from (
	select * from tb_student
) b

Nested queries require tables to be aliased

with query

When the result of a query is used multiple times in SQL, you can use with to create a temporary table for query

with temp as ( select * from tb_student) select * from temp ;

Association query

What relationship exists between tables??? What relationship exists between data???

  • One-To-One :
  • Many-To-One:
  • One-To-Many:
  • Many-To-Many:

one-to-one relationship

User table: (id, username, password, registration time, last login time, last login IP address, account status)

User information form (ID, ID number, profile photo, gender, date of birth, mobile phone number, email)

create table tb_user(
	id bigint primary key auto_increment ,
	username varchar(50) unique not null comment '用户名' ,
	password varchar(128) not null comment '密码', 
	last_login_time datetime comment '最近登录时间', 
	ip_addr varchar(100) comment '最近登录IP', 
	status tinyint default 0 comment  '-1 注销 0 未激活  1 正常  -2 拉黑' ,
	create_time datetime comment '注册时间' 
);

-- 常规创建
create table tb_user_info (
   id bigint primary key auto_increment ,
   card varchar(18) comment '身份证号', 
   photo varchar(200) comment '头像地址' ,
   sex enum('m', 'f', 's') default 's' comment '性别' ,
   birth date comment '出生日期', 
   tel varchar(11) comment '手机号', 
   email varchar(50) comment '邮箱' ,
   -- 维护关系
   user_id bigint unique, 
   -- 添加外键约束 	
   foreign key(user_id) references tb_user(id)
) ;

-- 主键共享 
create table tb_user_info (
   id bigint primary key auto_increment ,
   card varchar(18) comment '身份证号', 
   photo varchar(200) comment '头像地址' ,
   sex enum('m', 'f', 's') default 's' comment '性别' ,
   birth date comment '出生日期', 
   tel varchar(11) comment '手机号', 
   email varchar(50) comment '邮箱' ,
   foreign key(id) references tb_user(id)
) ;

Many-to-one or one-to-many relationship

It is the relationship that relational databases are best at handling, and it is also the most common relationship in life.
The relationship is maintained by more than one party

create table tb_resource_type(
	id bigint primary key auto_increment ,
	name varchar(100) comment '资源类型名称' ,
	pid  bigint ,
	foreign key(pid) references tb_resource_type(id)
) ;

create table tb_resource(
   id bigint primary key auto_increment, 
   name varchar(200) comment '资源名称' ,
   descp text comment '资源描述', 
   keywords varchar(200) comment '关键字', 
   
   type_id bigint comment '资源类型ID', 
   
   score int comment '资源积分' ,
   resource varchar(200) comment '资源路径', 
   size bigint comment '文件大小', 
   ext varchar(20) comment '资源扩展名' ,
   create_time datetime comment '资源上传时间' ,
	
   user_id bigint comment '上传者' ,
   
   foreign key (type_id) references tb_resource_type(id) ,
   foreign key(user_id) references tb_user(id)
);

many-to-many relationship

Relational databases are least good at dealing with relationships.
Many-to-many associations are 中间表maintained

create table tb_role(
   id bigint primary key auto_increment ,
   name varchar(100) comment '角色名' , 
   descp varchar(500) comment '角色描述' ,
   status boolean default 1 comment '角色状态是否启用'
);

-- 用户和角色 中间表 (常规建表方式)
create table tb_role_user(
	id bigint primary key auto_increment ,
	role_id bigint ,
	user_id bigint ,
	foreign key(role_id) references tb_role(id), 
	foreign key(user_id) references tb_user(id)
);

-- 联合主键 构建中间表
create table tb_role_user(
	role_id bigint ,
	user_id bigint ,
	foreign key(role_id) references tb_role(id), 
	foreign key(user_id) references tb_user(id),
	
	primary key(role_id , user_id)
);

Association query

  • inner join : Inner link query, the inner keyword can be omitted

  • left outer join : left outer join query, the outer keyword can be omitted

  • right outer join : right outer join query, you can omit the outer keyword

Cartesian product (not recommended)

Merge multiple tables together for query

select r.*, t.name as typename from tb_resource r,  tb_resource_type t 
	where r.type_id = t.id ;

Extremely low performance: two tables will be cross-combined to form a super representative, the data volume rows of the table = rows of table A * rows of table B

Association query


select .... from A表  
	
	[left/right/inner] join B表  on 关联条件 
	
where ....

collection query

  • union
  • intersection
  • difference set

MySQL database only supports union query

Union / union all

Merge two SQLs together using union / union all to form one SQL.
union will deduplicate the results of two SQL queries.
union all only merges two SQL results without deduplication

The number of fields in the two SQL queries must be the same, and the meanings correspond to each other

Guess you like

Origin blog.csdn.net/weixin_52953038/article/details/126660985