MySQL study notes 04 [database query operations, today's content, table constraints]

  • MySQL Document-Dark Horse Programmer (Tencent Weiyun): https://share.weiyun.com/RaCdIwas
  • 1-MySQL foundation.pdf, 2-MySQL constraints and design.pdf, 3-MySQL multi-table query and transaction operation.pdf
  1. MySQL study notes 01 [database concept, MySQL installation and use] [day01]
  2. MySQL study notes 02 [SQL basic concepts and general grammar, database CRUD operations] [day01]
  3. MySQL study notes 03 [CRUD operations of database tables, basic operations recorded in database tables, client-side graphical interface tool SQLyog] [day01]

  4. MySQL study notes 04 [database query operations, table constraints] [day01, day02]

  5. MySQL study notes 05 [multi-table operation, three paradigms, database backup and restore] [day02]

  6. MySQL study notes 06 [multi-table query, sub-query, multi-table query exercises] [day03]

  7. MySQL study notes 07 [transaction, user management and authority management] [day03]

table of Contents

Database terminal operation error

07 Database query operation

DQL_Basic query

Remove duplicate result sets

Calculate the sum of scores

Alias

DQL_condition query

DQL_Basic query_Fuzzy query

Today's content

DQL_sort query

DQL_aggregate function

DQL_Group query

DQL_Paging query

08 Table constraints

Constraints_Overview

Constraint_non-empty constraint

Constraint_Unique Constraint

Constraint_primary key constraint

Constraint_Primary Key Constraint_Auto Growth

Constraints_Foreign Key Constraints

Foreign key constraints-examples of defects

Foreign key constraints related concepts

Constraint_Foreign Key Constraint_Cascade Operation

Cascade update

Cascade delete


Database terminal operation error

The command that reported the error: ERROR 1366 (HY000): Incorrect string value:'\xC3\xFB\xD7\xD6' for column'n

Solution (link to the original text): https://blog.csdn.net/u013317172/article/details/82778785

Many people will get this error when inserting Chinese data into the table after installing Mysql database.
ERROR 1366 (HY000): Incorrect string value:'\xD5\xC5\xD0\xA1\xC3\xF7' for column'NAME' at row 1
Insert picture description here

solution:

1. First find the Mysql database installation path, as shown below:

Insert picture description here

2. Find the my.ini file in this folder, find "default-character-set=utf8" in it, and modify uft8 to gbk.

Insert picture description here

Log in to the mysql database again to add Chinese data.

07 Database query operation

DQL_Basic query

1. Query of multiple fields

  • select field name 1, field name 2... from table name;
  • Note: If you query all fields, you can use * to replace the field list.

2. Remove duplication:

  • distinct

3. Calculated column

  • Generally, you can use the four arithmetic calculations to calculate a series of values ​​(usually only numerical calculations).
  • ifnull(expression1,expression2): The calculation result of null participation is null.
    • Expression 1: Which field needs to be judged whether it is null
    • If the field is null, the replacement value.

4. Make an alias:

  • as: as can be omitted.
CREATE TABLE student (
  id INT,
  -- 编号
  NAME VARCHAR (20),
  -- 姓名
  age INT,
  -- 年龄
  sex VARCHAR (5),
  -- 性别
  address VARCHAR (100),
  -- 地址
  math INT,
  -- 数学
  english INT-- 英语
) ;

INSERT INTO student(id,NAME,age,sex,address,math,english) VALUES 
(1,'马云',55,'男','杭州',66,78),
(2,'马化腾',45,'女','深圳',98,87),
(3,'马景涛',55,'男','香港',56,77),
(4,'柳岩',20,'女','湖南',76,65),
(5,'柳青',20,'男','湖南',86,NULL),
(6,'刘德华',57,'男','香港',99,99),
(7,'马德',22,'女','香港',99,99),
(8,'德玛西亚',18,'男','南京',56,65);

SELECT * FROM student;

   

Remove duplicate result sets

Calculate the sum of scores

Alias

DQL_condition query

1. where clause followed by conditions

2. Operator

  • > 、< 、<= 、>= 、= 、<>
  • BETWEEN...AND  
  • IN (collection) 
  • LIKE: fuzzy query
    • Placeholder:
      • _: any single character
      • %: multiple arbitrary characters
  • IS NULL  
  • and  或 &&
  • or  或 || 
  • not or!
-- 查询年龄大于20岁
SELECT 
  * 
FROM
  student 
WHERE age > 20 ;
SELECT * FROM student WHERE age >= 20;

-- 查询年龄等于20岁
SELECT * FROM student WHERE age = 20;

-- 查询年龄不等于20岁
SELECT * FROM student WHERE age != 20;
SELECT * FROM student WHERE age <> 20;

-- 查询年龄大于等于20 小于等于30
SELECT * FROM student WHERE age >= 20 &&  age <=30;
SELECT * FROM student WHERE age >= 20 AND  age <=30;
SELECT * FROM student WHERE age BETWEEN 20 AND 30; -- 闭区间[20, 30]

-- 查询年龄22岁,18岁,25岁的信息
SELECT * FROM student WHERE age = 22 OR age = 18 OR age = 25
SELECT * FROM student WHERE age IN (22,18,25);

-- 查询英语成绩为null
SELECT * FROM student WHERE english = NULL; -- 错误!null值不能使用 = (!=) 判断

SELECT * FROM student WHERE english IS NULL;

-- 查询英语成绩不为null
SELECT * FROM student WHERE english  IS NOT NULL;

DQL_Basic query_Fuzzy query

LIKE: fuzzy query

  • Placeholder:
    • _: any single character
    • %: multiple arbitrary characters
-- 查询姓马的有哪些? like
SELECT 
  * 
FROM
  student 
WHERE NAME LIKE '马%' ;

-- 查询姓名第二个字是化的人
SELECT * FROM student WHERE NAME LIKE "_化%";

-- 查询姓名是3个字的人
SELECT * FROM student WHERE NAME LIKE '___';

-- 查询姓名中包含德的人
SELECT * FROM student WHERE NAME LIKE '%德%';

Today's content

  1. DQL: query statement
    1. Sort query
    2. Aggregate function
    3. Group query
    4. Paging query
  2. constraint
  3. Relationship between multiple tables
  4. Paradigm
  5. Database backup and restore

DQL_sort query

1. Sort query

  • Syntax: order by clause
    • order by sorting field 1 sorting method 1, sorting field 2 sorting method 2...
  • sort by:
    • ASC: Ascending order (default).
    • DESC: descending order.
  • note:
    • If there are multiple sorting conditions, the second condition will be judged when the condition value of the current side is the same.

DQL_aggregate function

2. Aggregate function: Take a column of data as a whole and perform vertical calculations.

  1. count: count the number
    1. Generally select non-empty columns: primary key
    2. count(*)
  2. max: calculate the maximum value
  3. min: calculate the minimum value
  4. sum: calculate the sum
  5. avg: calculate the average

Note: The calculation of aggregate functions excludes null values.

Solution: 1. Select columns that do not contain non-empty for calculation; 2. IFNULL function.

  

DQL_Group query

3. Group query:

  1. Syntax: group by group field;
  2. note:
    1. Fields to be queried after grouping: grouping fields, aggregate functions
    2. The difference between where and having?
      1. Where is defined before grouping, if the conditions are not met, it will not participate in grouping. Having limited after grouping, if the result is not satisfied, it will not be queried
      2. Aggregate functions cannot be followed after where, and having aggregate functions can be judged.
-- 按照性别分组。分别查询男、女同学的平均分
SELECT sex , AVG(math) FROM student GROUP BY sex;
		
-- 按照性别分组。分别查询男、女同学的平均分,人数
SELECT sex , AVG(math), COUNT(id) FROM student GROUP BY sex;
		
-- 按照性别分组。分别查询男、女同学的平均分,人数 要求:分数低于70分的人,不参与分组
SELECT sex , AVG(math), COUNT(id) FROM student WHERE math > 70 GROUP BY sex;

-- 按照性别分组。分别查询男、女同学的平均分,人数 要求:分数低于70分的人,不参与分组,分组之后。人数要大于2个人
SELECT sex , AVG(math), COUNT(id) FROM student WHERE math > 70 GROUP BY sex HAVING COUNT(id) > 2;
SELECT sex , AVG(math), COUNT(id) 人数 FROM student WHERE math > 70 GROUP BY sex HAVING 人数 > 2;

DQL_Paging query

4. Paging query

  1. Syntax: index starting with limit, the number of queries per page;
  2. Formula: starting index = (current page number-1) * number of items displayed on each page
    1. 3 records per page 
    2. SELECT * FROM student LIMIT 0,3; - Page 1: Check from 0, check 3 records
    3. SELECT * FROM student LIMIT 3,3; - Page 2: Check from 3, check 3 records
    4. SELECT * FROM student LIMIT 6,3; - Page 3:
  3. limit is a MySQL "dialect"

08 Table constraints

Constraints_Overview

Concept: Limit the data in the table to ensure the correctness, validity and completeness of the data.    

classification:

  1. Primary key constraint: primary key
  2. Non-empty constraint: not null
  3. The only constraint: unique
  4. Foreign key constraint: foreign key

Constraint_non-empty constraint

Non-empty constraint: not null, the value cannot be nul

    1. When creating a table, add the constraint
        CREATE TABLE stu(
            id INT,
            NAME VARCHAR(20) NOT NULL - name is not empty
        );
    2. After creating the table, add a non-empty constraint: ALTER TABLE stu MODIFY NAME VARCHAR(20 ) NOT NULL ;

    3. Delete the non-empty constraint of name: ALTER TABLE stu MODIFY NAME VARCHAR(20);

  

Constraint_Unique Constraint

Unique constraint: unique, the value cannot be repeated.

    1. When creating a table, add a unique constraint
        CREATE TABLE stu(
            id INT,
            phone_number VARCHAR(20) UNIQUE - a unique constraint is added
        );
        * Note that in mysql, the value of a column limited by a unique constraint can have multiple nulls.

    2. Delete the unique constraint: ALTER TABLE stu DROP INDEX phone_number;

    3. After creating the table, add a unique constraint: ALTER TABLE stu MODIFY phone_number VARCHAR(20) UNIQUE;

Constraint_primary key constraint

Primary key constraint: primary key

    1. Note:
        1. Meaning: non-empty and unique
        2. A table can only have one field as the primary key
        3. The primary key is the unique identifier of the record in the table

    2. When creating a table, add a primary key constraint
        create table stu(
            id int primary key, - add a primary key constraint
            name varchar(20)
        ) to id ;

    3. Delete the primary key
        - error alter table stu modify id int;
        ALTER TABLE stu DROP PRIMARY KEY;

    4. After creating the table, add the primary key
        ALTER TABLE stu MODIFY id INT PRIMARY KEY;

Constraint_Primary Key Constraint_Auto Growth

    5. Automatic growth:
        1. Concept: If a column is of numeric type, use auto_increment to complete the automatic growth

        2. When creating the table, add the primary key constraint, and complete the primary key self-growth
        create table stu (
            id int primary key auto_increment, - add primary key constraint
            name varchar(20)
        ) to id ;

        3. Delete automatic growth: ALTER TABLE stu MODIFY id INT;

        4. Add automatic growth: ALTER TABLE stu MODIFY id INT AUTO_INCREMENT;

Constraints_Foreign Key Constraints

Foreign key constraints-examples of defects

CREATE TABLE emp ( -- 创建employe表
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(30),
	age INT,
	dep_name VARCHAR(30), -- 部门名称
	dep_location VARCHAR(30) -- 部门地址
);

-- 添加数据
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('张三', 20, '研发部', '广州');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('李四', 21, '研发部', '广州');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('王五', 20, '研发部', '广州');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('老王', 20, '销售部', '深圳');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('大王', 22, '销售部', '深圳');
INSERT INTO emp (NAME, age, dep_name, dep_location) VALUES ('小王', 18, '销售部', '深圳');

-- 解决方案:分成 2 张表

-- 创建部门表(id,dep_name,dep_location)
-- 一方,主表
CREATE TABLE department(
	id INT PRIMARY KEY AUTO_INCREMENT,
	dep_name VARCHAR(20),
	dep_location VARCHAR(20)
);

-- 创建员工表(id,name,age,dep_id)
-- 多方,从表
CREATE TABLE employee(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(20),
	age INT,
	dep_id INT -- 外键对应主表的主键
);

-- 添加 2 个部门
INSERT INTO department VALUES(NULL, '研发部','广州'),(NULL, '销售部', '深圳');
SELECT * FROM department;

-- 添加员工,dep_id 表示员工所在的部门
INSERT INTO employee (NAME, age, dep_id) VALUES ('张三', 20, 1);
INSERT INTO employee (NAME, age, dep_id) VALUES ('李四', 21, 1);
INSERT INTO employee (NAME, age, dep_id) VALUES ('王五', 20, 1);
INSERT INTO employee (NAME, age, dep_id) VALUES ('老王', 20, 2);
INSERT INTO employee (NAME, age, dep_id) VALUES ('大王', 22, 2);
INSERT INTO employee (NAME, age, dep_id) VALUES ('小王', 18, 2);

SELECT * FROM employee;
SELECT * FROM department;

Foreign key constraints related concepts

* Foreign key constraints: foreign key, let the table and the table have a relationship, so as to ensure the correctness of the data.

    1. When creating a table, you can add a foreign key
        * Syntax:
            create table table name (
                ...
                foreign key column
                constraint foreign key name foreign key (foreign key column name) references main table name (main table column name)
            );

    2. Delete the foreign key
        ALTER TABLE table name DROP FOREIGN KEY foreign key name;

    3. After the table is created, add the foreign key
        ALTER TABLE table name ADD CONSTRAINT foreign key name FOREIGN KEY (foreign key field name) REFERENCES main table name (main table column name); // primary key column, unique constraint column

CREATE TABLE employee(
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(20),
    age INT,
    dep_id INT, - the foreign key corresponds to the primary key of the primary table
    CONSTRAINT emp_dept_fk FOREIGN KEY (dep_id) REFERENCES department(id) - foreign key constraint
);

 

Constraint_Foreign Key Constraint_Cascade Operation

4. Cascade operation
    1. Add cascade operation
        syntax: ALTER TABLE table name ADD CONSTRAINT foreign key name 
                    FOREIGN KEY (foreign key field name) REFERENCES main table name (main table column name) ON UPDATE CASCADE ON DELETE CASCADE;
    2. Classification :
        1. Cascade update: ON UPDATE CASCADE 
        2. Cascade delete: ON DELETE CASCADE 

Cascade update

Cascade delete

What's the beginning of spring? Open up your horizons, open your mind, open up your wisdom, open up the pattern!

Lichun, what is it? Relying on benevolence, righteousness, loyalty, sincerity, and spirit!

Guess you like

Origin blog.csdn.net/weixin_44949135/article/details/113631792