DQL (conditional query)

DQL (conditional query)

Condition query:

Use the WHERE clause to filter out the rows that do not meet the conditions. The WHERE clause immediately follows the FROM clause.

Syntax : select <result> from <table name> where <condition>

Comparison: =, != or <>, >, <, >=, <=

logic operation

​ and and

​ or 或

​ not

(1) Fuzzy query

LIKE : Whether it matches a pattern is generally used in conjunction with wildcards, and it can be judged whether it is a character value or a numeric value.

Wildcard:% Any number of characters, including 0 characters _ Any single character

between and between the two, including the critical value;

in Determine whether the value of a field belongs to an item in the in list

IS NULL (empty) or IS NOT NULL (not empty)

UNION (connection):

It is used more. Union all is a direct connection, and all values ​​are obtained. The record may have duplicates. Union is a unique value, and the record is not duplicated.

1. The syntax of UNION is as follows:

​ [SQL statement 1]

​ UNION

​ [SQL statement 2]

2. The syntax of UNION ALL is as follows:

​ [SQL statement 1]

​ UNION ALL

​ [SQL statement 2]

effectiveness:

The UNION and UNION ALL keywords combine two result sets into one, but they are different in terms of usage and efficiency.

1. Treatment of duplicate results: UNION will filter out duplicate records after table linking, and Union All will not remove duplicate records.

2. Processing of sorting: Union will sort according to the order of the fields; UNION ALL simply combines the two results and returns.

In terms of efficiency, UNION ALL is much faster than UNION, so if you can confirm that the merged two result sets do not contain duplicate data and do not require sorting, then UNION ALL is used.

Sort:
  • The query results are sorted, using the ORDER BY clause to sort order by ASC/DESC

  • asc represents ascending order, desc represents descending order, if not written, the default is ascending order

  • Single field, multiple fields, expressions, functions, aliases can be supported in the order by clause

Quantitative restrictions:
  • limit clause: limit the number of displayed results of the query (the last position of the SQL statement)

  • SELECT * FROM table LIMIT [offset,] rows | rows OFFSET offset;

  • SELECT * FROM table LIMIT 5;

  • SELECT * from table LIMIT 0,5;

  • SELECT * FROM table LIMIT 2 OFFSET 3;

-- 查询语法
-- select 结果 from 表名 where 数据条件过滤  group by having  order by limit

SELECT * FROM t_student 
-- =在where子句后面表示 等于
SELECT * FROM t_student  WHERE stu_sex='男'

SELECT * FROM t_student  WHERE stu_sex!='男'

SELECT * FROM t_student  WHERE stu_sex<>'男'
-- and 多个条件的并列,必须全部成立
SELECT * FROM t_student  WHERE stu_score >60  AND stu_sex='女'
-- or  多个条件只要满足一个即可
SELECT * FROM t_student  WHERE stu_score >60  OR stu_sex='男'
-- 查询成绩合格的学生  >=60  <=100
SELECT * FROM t_student  WHERE stu_score >=60  AND  stu_score <=100
-- 列名 BETWEEN 区间开始 and 区间结束  包含60 100
SELECT * FROM t_student  WHERE stu_score BETWEEN 60  AND 100


-- 模糊查询
-- like

SELECT * FROM t_student WHERE stu_name='锦涛';

-- 查询姓张的人
-- like '关键字 % _' %匹配多个字符  _只能匹配一个字符
SELECT * FROM t_student WHERE stu_name LIKE'张%';
SELECT * FROM t_student WHERE stu_name LIKE'张_';

SELECT * FROM t_student WHERE stu_name LIKE'%涛';

-- 查询成绩为80和90的学生
-- in(值1 ,值2 ...)
SELECT * FROM t_student WHERE stu_score= 80 OR stu_score=90
SELECT * FROM t_student WHERE stu_score IN(80,90,100)

-- not 不在 不是
SELECT * FROM t_student WHERE stu_score NOT IN(80,90,100)

-- 查询性别不为空
-- is null 为null  is not null 不为空
SELECT * FROM t_student WHERE stu_sex IS NULL
SELECT * FROM t_student WHERE stu_sex IS NOT NULL

/*
union 将多个查询结果合并,要求查询出来的列数相同

sql1
 union   可以去重复元素,对结果进行排序
 sql2

union   /  union all
*/
SELECT stu_name,stu_num FROM t_student WHERE stu_sex ='女'

UNION
SELECT stu_name,stu_num FROM t_student WHERE stu_sex ='女'

-- union all 只是粗暴的合并
SELECT stu_name,stu_num FROM t_student WHERE stu_sex ='女'

UNION ALL
SELECT stu_name,stu_num FROM t_student WHERE stu_sex ='女'



-- order by 排序
-- 默认使用主键  升序排列
SELECT * FROM t_student

SELECT * FROM t_student  ORDER BY stu_score ASC
-- 指定排序
SELECT * FROM t_student  ORDER BY stu_score DESC
-- 在条件后面加排序
SELECT * FROM t_student WHERE stu_sex='女'  ORDER BY stu_score ASC

-- 行数限制
-- SELECT * FROM table  LIMIT [offset,] rows | rows OFFSET offset;

-- 提取前三条数据      
SELECT * FROM t_student  LIMIT 3

-- 查询成绩前俩名的学生 						查询前俩条
SELECT * FROM t_student  WHERE  stu_score>0  ORDER BY stu_score DESC   LIMIT 2
--   limit 开始位置(从0开始),数量
SELECT * FROM t_student  WHERE  stu_score>0  ORDER BY stu_score DESC   LIMIT 0,2

-- limit  行数 offset  位置
SELECT * FROM t_student  WHERE  stu_score>0  ORDER BY stu_score DESC   LIMIT 2 OFFSET 0

(2) Group query

grammar:

select grouping function, column (required to appear after group by)

from 表

[where filter condition]

group by grouped list

[Filtering after grouping]

[order by clause]

Note : The query list is quite special, the requirement is the grouping function and the field after group by

The filter conditions in the group query are divided into two categories:

​ Data source source location keywords

  • Filter the front where of the original table group by clause before grouping

  • After grouping, filter the grouped result set after group by having

-- 分组查询  分组   会将相同内容分到同一个组   例如使用性别分组
-- 男 2
-- 女 2
-- select 结果  from 表 gronp by 分组列

-- 统计男生女生各有多少人
SELECT stu_sex,COUNT(*)  FROM t_student GROUP BY stu_sex
SELECT stu_sex,MAX(stu_score)  FROM t_student GROUP BY stu_sex


-- 添加查询条件

SELECT stu_sex,COUNT(*) c 
FROM t_student 
WHERE stu_score>0 -- 在分组前对数据进行筛选过滤
GROUP BY stu_sex
ORDER BY c DESC  -- 对分组后的结果进行排序
LIMIT 1

-- 查询性别人数大于2的  是哪个性别   对分组后的结果进行筛选过滤
SELECT stu_sex,COUNT(*) c 
FROM t_student 
WHERE stu_score>0 
GROUP BY stu_sex
HAVING c>=2      -- 对分组后的结果进行条件过滤
ORDER BY c DESC  

(3) Subquery

Meaning : the select statement that appears in other statements is called subquery or inner query; the external query statement is called main query or

(1) Classification:

By the position where the subquery appears:

  • After select: only supports scalar subqueries

  • After from: support table subquery

  • After where or having: support scalar subquery, column subquery, row subquery (less)

  • Behind exists (related subquery): support table subquery

According to the function, the number of rows and columns of the result set is different:

  • Scalar sub-query (the result set has only one row and one column)

  • Column query (the result set has only one column and multiple rows)

  • Row subquery (the result set has one row and multiple columns)

  • Table subquery (the result set is generally multi-row and multi-column)

The SELECT statement can appear in the subquery inside the SELECT statement.

The result of the statement can be used as a part of the conditional clause in the external statement, or as a temporary table of the external query.

For example : insert information about the student with the highest grade

-- 子查询:出现在其他语句中的select 语句
-- 其他语句: insert ,update,delete,select

-- 在insert 语句中使用子查询
INSERT INTO t_student(stu_name,stu_sex) SELECT stu_name,stu_sex FROM t_student WHERE stu_num=2
-- 在update 语句中使用子查询  注意查询的结果不能在本张表查询
UPDATE t_student SET stu_name='王珊珊' WHERE stu_num=(SELECT stu_num FROM stu_temp WHERE stu_num=2 )

CREATE TABLE stu_temp(
	stu_num INT,
	stu_name VARCHAR(10)
)
 
 
 -- 在select语句中使用子查询
 
 /*
按照子查询结果分为
标量子查询(一行一列) 
列子查询(一列多行)
行子查询(一行多列)
表子查询(多行多列)


按子查询出现的位置:
select后面:仅仅支持标量子查询
from后面:支持表子查询
where或having后面:支持标量子查询,列子查询,行子查询(较少)
exists后面(相关子查询):支持表子查询

 */
 
-- 在select 语句加子查询,只能是标量子查询 
SELECT  stu_name,(SELECT NOW()),stu_num FROM t_student

-- 表子查询   八查询结果当做一张表处理
SELECT * FROM 
 (SELECT stu_sex,COUNT(*) c FROM t_student GROUP BY stu_sex)t
 WHERE t.c>2
-- 列子查询
SELECT * FROM t_student
WHERE stu_socre IN(SELECT stu_score FROM t_student WHERE stu_score>50) 
 
 
(4) Association query-multi-table design

Data redundancy-split

Database design paradigm
  • In order to build a database with less redundancy and a reasonable structure, certain rules must be followed when designing the database. In relational databases, such rules are called paradigms. A paradigm is a summary that meets a certain design requirement.

  • There are currently 5 paradigms in relational databases: First Normal Form (1NF), Second Normal Form (2NF), Third Normal Form (3NF), Bath-Cord Normal Form (BCNF), Fourth Normal Form (4NF) and Fifth Normal Form ( 5NF, also known as perfect paradigm).

  • The paradigm that meets the minimum requirements is the first normal form (1NF). On the basis of the first normal form, the one that further satisfies more specifications is called the second normal form (2NF), and the rest of the normal form can be deduced by analogy. Generally speaking, the database only needs to satisfy the third normal form (3NF).

(1) The first normal form (ensure that each column remains atomic) The column cannot be divided

The first paradigm is the most basic paradigm. If all field values ​​in the database table are non-decomposable atomic values, it means that the database table satisfies the first normal form.

(2) Second normal form

It is to have a primary key, requiring other fields to depend on the primary key. Without the primary key, there is no uniqueness, and without uniqueness, this row of records cannot be located in the collection, so the primary key is required.

(3) Third Normal Form

It is to eliminate transitive dependence and facilitate understanding, which can be regarded as "eliminating redundancy".

Foreign key:

Refer to a record of another data table.

The foreign key column type is consistent with the primary key column type

The association/reference relationship between the data tables is established by the specific primary key and foreign key.

Add foreign key constraint syntax

ALTER TABLE table name ADD [CONSTRAINT constraint name] FOREIGN KEY (foreign key column) REFERENCES associated table (primary key);

Delete foreign key syntax

ALTER TABLE table name DROP FOREIGN KEY foreign key constraint name

note

(1) When there is no corresponding record in the master table, the record cannot be added to the slave table

(2) The value in the main table cannot be changed and the records in the slave table are isolated

(3) There is a record corresponding to the main table from the table, and the row cannot be deleted from the main table

(4) Before deleting the master table, delete the slave table

/*
多表设计
   设计表时:先确定存储那类信息,学生表,定义列,数据类型 的约束
   学生表
   老师表
   课程表
   需要存储不同的信息(一张表中只能存储一类信息)
   
   
   学生表
		民族,年级
   老师表
		民族,年级
    员工表
		编号,姓名,性别,部门编号
    部门表
		部门编号,部门名称
		
		
	学生表,年级表,课程表
	表与表之间常见的几种关系
	
	
	一对一关联(例如 一个学生只能对应一个年级)
	一对多关联(一个年级对应多个学生)
	多对一关联(多个学生对应一个年级)
	多对多关联
	
	学生表,
		学号,姓名,性别,手机号,年级编号,注册时间
	年级表,
		年级编号,年级名称,年级介绍
	课程表,
		课程编号,课程名称,课程介绍
*/
DROP TABLE t_dent;
CREATE TABLE grade(
		id INT PRIMARY KEY AUTO_INCREMENT,
		NAME VARCHAR(10),
		gdesc VARCHAR(50) 
)
CREATE TABLE student(
		num INT PRIMARY KEY AUTO_INCREMENT,
		NAME VARCHAR(10),
		sex CHAR(1),
		phone VARCHAR(11),
		grade_id INT,
		reg_time DATETIME
)

-- 弱关联关系  表与表之间的关系是人为定义的,表结构中并没有实际联系


-- 强关联关系,给外键添加约束,强制让外键与对应的主键产生关系(外键 对应的都是另一个表中的主键)


-- 修改学生表    把gread_id设置为外键  并添加约束名   指定gread_id与gread表中的id列对应
ALTER TABLE student ADD CONSTRAINT grade_id_fk FOREIGN KEY (grade_id) REFERENCES grade(id)

-- 多对多关系
-- 学生与课程的关系  一个学生对应多个课程  一个课程对应多个学生
-- 设计一个关系表,来存储多个之间的关系
CREATE TABLE student_course(
		id INT PRIMARY KEY AUTO_INCREMENT,
		stu_num INT,
		NAME VARCHAR(10),
		course_id INT,
		CONSTRAINT  stu_num_fk FOREIGN KEY (stu_num) REFERENCES student(num),
		CONSTRAINT  course_id_fk FOREIGN KEY (course_id) REFERENCES course(id)

)
ALTER TABLE  student_course  DROP NAME

CREATE TABLE course(
		id INT PRIMARY KEY AUTO_INCREMENT,
		NAME VARCHAR(10),
		vdeac VARCHAR(10)
)


(4) Related queries-continued

Meaning : also known as multi-table query, when the query field comes from multiple tables, it will use join query

Cartesian product phenomenon : Table 1 has m rows, Table 2 has n rows, the result = m*n

  • Cause: There is no valid connection condition

  • How to avoid: add valid connection conditions

Classified by function:

  1. Internal connection

Insert picture description here

Equivalent connection

Non-equivalent join

Self-connection

Concept: Query the intersection data in the two tables that meet the conditions

Syntax: Select result from table 1, table 2 where table 1.column1 = table 2.column2

​ 2. External connection

Left outer join

Insert picture description here

Syntax: select result from table 1 leftjoin table 2 on table 1.column1 = table 2.column2

Right outer join
Insert picture description here

select result from table 1 right join table 2 on table 1.column1 = table 2.column2

Cross connect

-- 笛卡尔乘积
 SELECT
  *
FROM
  student,
  grade -- 内连接
   -- 等值连接
-- 查询学生信息,学号,姓名,性别,年级名称
   SELECT
    student.num,
    student.name,
    student.sex,
    grade.name
  FROM
    student
    INNER JOIN grade
      ON student.grade_id = grade.id 
      
      
      -- -----------
      -- 为表名定义别名,然后通过别名来访问表中的列
         SELECT
    s.num,
    s.name,
    s.sex,
    s.grade_id,
    g.name,
    g.id
    
  FROM
    student AS s
    INNER JOIN grade g
      ON s.grade_id = g.id     -- on 后面是俩张表关联条件, 与where后面的条件有区别
      
      -- 使用where条件过滤
           SELECT
    s.num,
    s.name,
    s.sex,
    s.grade_id,
    g.name,
    g.id
    
  FROM
    student  s,
     grade g
     WHERE s.grade_id = g.id  
      
 -- 非等值连接
ALTER TABLE student ADD score INT      
-- 成绩等级表
CREATE TABLE score_level(
		NAME VARCHAR(10),
		lower_score INT,
		upper_score INT
)
SELECT
  s.name,
  sl.name
FROM
  student s
  INNER JOIN score_level sl
    ON s.score BETWEEN sl.lower_score
    AND sl.upper_score
    
    
       -- 自连接
       
CREATE TABLE t_area(
		id INT,
		NAME VARCHAR(10),
		pid INT
)

SELECT * FROM t_area t1 INNER JOIN t_area t2 ON t1.pid=t2.id
-- 外连接
-- 左外连接
ALTER TABLE student ADD CONSTRAINT  FOREIGN KEY (grade_id) REFERENCES grade(id)

SELECT * FROM student s LEFT JOIN grade g ON s.grade_id=g.id


-- 右外连接

SELECT * FROM student s RIGHT JOIN grade g ON s.grade_id=g.id

-- 交叉连接
SELECT * FROM student s CROSS JOIN grade g ON s.grade_id=g.id


JOIN score_level sl
ON s.score BETWEEN sl.lower_score
AND sl.upper_score

   -- 自连接

CREATE TABLE t_area(
id INT,
NAME VARCHAR(10),
pid INT
)

SELECT * FROM t_area t1 INNER JOIN t_area t2 ON t1.pid=t2.id


```mysql
-- 外连接
-- 左外连接
ALTER TABLE student ADD CONSTRAINT  FOREIGN KEY (grade_id) REFERENCES grade(id)

SELECT * FROM student s LEFT JOIN grade g ON s.grade_id=g.id


-- 右外连接

SELECT * FROM student s RIGHT JOIN grade g ON s.grade_id=g.id

-- 交叉连接
SELECT * FROM student s CROSS JOIN grade g ON s.grade_id=g.id


Guess you like

Origin blog.csdn.net/ZJ_1011487813/article/details/112992520