Constraints and queries of MySQL tables

1. Table constraints:

1. Constraint type:

NOT NULL -Indicates that a column cannot store NULL values.
UNIQUE -to ensure that each row of a column must have a unique value.
DEFAULT -specifies the default value when no value is assigned to the column.
PRIMARY KEY -a combination of NOT NULL and UNIQUE. Ensure that a column (or a combination of two columns and multiple columns) has a unique identifier, which helps to find a specific record in the table easier and faster.
FOREIGN KEY -to ensure the referential integrity of data in one table matching the values ​​in another table.
CHECK -to ensure that the values ​​in the column meet the specified conditions. For MySQL database, the CHECK clause is analyzed, but the CHECK clause is ignored

2. Null constraint:

When creating a table, you can specify that a column is not empty:

drop table if exists student; -- 如果有 student 这个表则删除
create table student (
    id int not null
);

3. Unique: unique constraint

Specify the sn list as unique and non-repetitive:

drop table if exists student;-- 如果有 student 这个表则删除
create table student (
    id int not null,
    sn int unique
);

4. Default: Default value constraints

When you specify to insert data, the name column is empty, and the default value is unkown:

drop table if exists student;-- 如果有 student 这个表则删除
create table student (
    id int not null,
    sn int unique,
    name varchar(20) default 'unkown'
);

5. Primary key: primary key constraint

Specify the id column as the primary key:

drop table if exists student;-- 如果有 student 这个表则删除
create table student (
    id int not null primary key,
    sn int unique,
    name varchar(20) default 'unkown'
);

For the primary key of integer type, it is often used with auto_increment . When the corresponding field of the inserted data does not give a value, the maximum value +1 is used

-- 主键是 NOT NULL 和 UNIQUE 的结合,可以不用 NOT NULL
id INT PRIMARY KEY auto_increment,

6, Foreign key: foreign key constraints

Other foreign key table for associating a primary key or a unique key

Create a class table classes, id as the primary key

-- 使用 MySQL 关键字作为字段时,需要使用 '' 来标识
DROP TABLE IF EXISTS classes;
CREATE TABLE classes (
    id INT PRIMARY KEY auto_increment,
    name VARCHAR(20),
    `desc` VARCHAR(100)
);

Create student table student, one student corresponds to one class, and one class corresponds to multiple students. Use id as the primary key,
classes_id as the foreign key, associated with the class table id

-- 重新设置学生表结构
DROP TABLE IF EXISTS student;
CREATE TABLE student (
    id INT PRIMARY KEY auto_increment,
    sn INT UNIQUE,
    name VARCHAR(20) DEFAULT 'unkown',

    classes_id int,
    FOREIGN KEY (classes_id) REFERENCES classes(id)
);

7. Check constraints:

No error is reported when MySQL is used, but the constraint is ignored:

drop table if exists test_user;
create table test_user (
   id int,
   name varchar(20),
   sex varchar(1),
   check (sex ='男' or sex='女')
);

2. Table query:

1. Aggregate query:

(1) Aggregate function:

function explain
count() The query data quantity
sum() Query data (number) of the total
avg() Query data (digital) of the average
max() Query data (digital) of the maximum value
min () Query data (digital) of the minimum

Give a chestnut:
① count:

-- 统计班级共有多少同学
SELECT COUNT(*) FROM student;
SELECT COUNT(0) FROM student;
-- 统计班级收集的 qq_mail 有多少个,qq_mail 为 NULL 的数据不会计入结果
SELECT COUNT(qq_mail) FROM student;

② sum:

-- 统计数学成绩总分
SELECT SUM(math) FROM exam_result;
-- 不及格 < 60 的总分,没有结果,返回 NULL
SELECT SUM(math) FROM exam_result WHERE math < 60;

③ avg:

-- 统计平均总分
SELECT AVG(chinese + math + english) '平均总分' FROM exam_result;

④ max:

-- 返回英语最高分
SELECT MAX(english) FROM exam_result;

⑤ min:

-- 返回 > 70 分以上的数学最低分
SELECT MIN(math) FROM exam_result WHERE math > 70;

(2) Group query (group by):

The GROUP BY clause can be used in SELECT to perform grouping query on the specified column.
Need to meet: when using GROUP BY for grouping query, the field specified by SELECT must be the "group by field", and other fields must be included in the aggregate function if they want to appear in the SELECT

Give a chestnut:
prepare a staff table, including id, name, role, salary

create table emp(
    id int primary key auto_increment,
    name varchar(20) not null,
    role varchar(20) not null,
    salary numeric(11,2)
);
insert into emp(name, role, salary) values
('孙悟空','刺客', 999.11),
('猪无能','坦克', 333.5),
('沙和尚','战士', 700.33),
('隔壁老王','董事长', 12000.66);

Query the maximum wage, minimum wage and average wage of each role

select role,max(salary),min(salary),avg(salary) from emp group by role;

having:
After the GROUP BY clause to group, the need for grouping the results of further criteria to filter , you can not use the WHERE clause, and HAVING need
to display the average wage of less than 1500 characters and its average wage:

select role,max(salary),min(salary),avg(salary) from emp group by role having avg(salary)<1500;

2. Joint query:

In actual development, data often comes from different tables, so multiple tables are required for joint query.

Multi-table query data from multiple tables to take Cartesian product :

(1) Internal connection and external connection:

The difference between inner connection and outer connection (interview):

(2) Self-connection:

Since the connection means in the same table connection own query:

Take a chestnut:
display all the score information of "Computer Principles" scores higher than "Java" scores

-- 先查询“计算机原理”和“Java”课程的id
select id,name from course where name='Java' or name='计算机原理';
-- 再查询成绩表中,“计算机原理”成绩比“Java”成绩 高的信息
SELECT s1.* FROM score s1, score s2 WHERE s1.student_id = s2.student_id
 AND s1.score < s2.score
 AND s1.course_id = 1
 AND s2.course_id = 3;
-- 也可以使用join on 语句来进行自连接查询
SELECT s1.* FROM score s1 JOIN score s2 ON s1.student_id = s2.student_id
 AND s1.score < s2.score
 AND s1.course_id = 1
 AND s2.course_id = 3;

The above query only shows the performance information, and is executed in a distributed manner.
To display student and grade information, and display it in a sentence:

SELECT stu.*, s1.score Java, s2.score 计算机原理 FROM score s1
 JOIN score s2 ON s1.student_id = s2.student_id
 JOIN student stu ON s1.student_id = stu.id
 JOIN course c1 ON s1.course_id = c1.id
 JOIN course c2 ON s2.course_id = c2.id
 AND s1.score < s2.score
 AND c1.NAME = 'Java'
 AND c2.NAME = '计算机原理';

(3) Subquery:

Subquery refers to embed in other sql statement select statement, also called a nested query
① single-row subquery: query returns a row of sub-
query "PubMed" classmate classmates:

select * from student where class_id = 
(select classes_id from student where name = '考研');

② Multi-line subquery: a subquery that returns multiple rows of records. Query
the score information of the "Chinese" or "English" course:

select * from score where course_id in 
(select id from course where name='语文' or name='英文');
select * from score sco where exists 
(select sco.id from course cou where (name='语文' or name='英文') and cou.id = sco.course_id);

(4) Combined query:

In practical applications, in order to merge the execution results of multiple selects, you can use the set operator union, union all. When using UNION and UNION ALL, the result set of the query before and after, the fields need to be consistent.

Union
The operator is used to obtain two sets of results , and set . When using this operator, it will automatically remove the result set of duplicate rows .
Query courses whose id is less than 3 or whose name is "English":

select * from course where id < 3 union
select * from course where name='英文';
-- 或者使用or来实现
select * from course where id<3 or name='英文';

Union All
the operator for acquiring the two result sets and set . When using this operator, will not remove the result set of duplicate rows .
Query courses whose id is less than 3 or whose name is "java"

-- 可以看到结果集中出现重复数据 java
select * from course where id < 3 union all 
select * from course where name = '英文';

Guess you like

Origin blog.csdn.net/qq_45658339/article/details/109732532