MySQL note organization + practice

First Normal Form (1NF)
Atomicity: Guarantee that each column cannot be further divided
Second Normal Form (2NF)
Premise: Satisfying the first normal form, each table only describes one thing
Premise: Satisfy the first normal form and the second normal form
Third Normal Form (3NF)
It is necessary to ensure that each column of data in the data table is directly related to the primary key, not indirectly.
#Query all databases
show databases;
#Query the current database
select database() ;
#create #if does not exist #charset #collation
create database if not exists stu1 default charset utf8mb4;   [collate]
#delete #if exists
drop database if exists stu1;
#use
use dbtext1;
#Query all tables in the current database
show tables;
# query table structure
desc stu ;
#Query the table creation statement of the specified table
show create table stu ;
create table stu (
id int comment 'number',
name varchar(50) comment 'name',
age int comment 'age',
gender varchar(1) comment 'gender'
);
desc stu;
#Increase
alter table stu add nick varchar(20);
alter table stu add nickname varchar(20) comment 'nickname';
alter table stu add idcard char(18);#ID card number
alter table stu add enteydate date;#birth date
# modify data type
alter table stu modify nickname varchar(10);
alter table stu modify age tinyint unsigned;
#Modify the field name and type
alter table stu change nick username varchar(30) comment 'username';
alter table stu add nick varchar(20);
#delete field
alter table stu drop nick;
alter table stu drop nickname;
# modify to show
alter table stu rename to stus;
alter table stus rename to stu;
# delete table
drop table if exists stu1;
#Delete the specified table and recreate the table
truncate table stu1;
1. Clear operation: DELETE FROM table_name ; will not reset the auto-increment field, which is inefficient, has log records, and will activate the trigger. For tables with a large amount of data, the execution is slower.
2. The truncation operation: TRUNCATE [TABLE] table_name ; will reset the auto-increment field, which is efficient, has no log records, and will not activate the trigger. Please use it with caution, once executed, the data cannot be recovered. Data is priceless, please be careful! ! (Don’t accidentally delete the library and run away_)
#data
select * from stu;
#insert, increase
insert into stu (id,name,age,gender)
values ​​(1,'Zhang San',23,'male');
insert into stu (username,idcard,enteydate)
values ​​('student',125455665565655556,'2001-03-12');
truncate table stu;
insert into stu (id,name,age,gender,username,idcard,enteydate)
values ​​(1,'Zhang San',23,'Male','Squad Leader',125455665565655556,'2001-03-12');
insert into stu values ​​(2,'Li Si',22,'male','deputy monitor',123456789012345678,'2001-09-12'),
(3,'Wang Wu',21,'Male','Member',125455665588855556,'2001-07-02');
#Revise
update stu set username = '学员' where id = 3;
update stu set gender = '女';
#delete
insert into stu (id,name)
values ​​(4,'haha');
delete from stu where id = 4;
#delete all data
delete from stu ;
#DCL
# query users
use mysql;
select * from `user` u ;
#Create a user to access on this machine
create user 'yh'@'localhost' identified by '123456';
# any host
create user 'yh'@'%' identified by '123456';
#change Password
alter user 'yh'@'localhost' identified with mysql_native_password by '123';
#delete
drop user 'yh'@'localhost' ;
# query permissions
show grants for 'yh'@'localhost';
#Granted permission
      #Authority #Database name. Indicates
grant all on dbtext1.* to 'yh'@'localhost';
# revoke permission
revoke all on dbtext1.* from 'yh'@'localhost';
#Multiple permissions are separated by commas. The library name indicates that all can be wildcarded with * to represent all
#all,all privileges all privileges
#select query permission.insert insert permission.update modify permission.delete delete permission.
#alter modify table.dorp delete database/table/view.create create database/table
-- Self Growth
-- auto-increment
-- not-null constraint
-- NOT NULL
-- unique constraint
-- UNIQUE
-- primary key constraint
-- PRIMARY KEY
-- check constraints MySQL does not support
-- CHECK
-- default constraints
-- DEFAULT
-- foreign key constraint
-- FOREIGN KEY
CONSTRAINT fk_emp_dept FOREIGN KEY(dep_id) REFERENCES dept(id)
use atguigudb;
select * from employees;
#distinct deduplication
select distinct department_id
from employees;
#distinct department_id , salary just did not report an error and has no practical meaning
select distinct department_id , salary
from employees;
#Empty value participates in the operation (null), null is not equal to 0," "
select * from employees;
#Empty value participating in the operation value is also empty
select employee_id, salary "monthly salary", salary * (1 + commission_pct)*12 "annual salary", commission_pct
from employees;
#Solution, introduce ifnull
select employee_id, salary "monthly salary", salary * (1 + ifnull(commission_pct,0))*12 "annual salary", commission_pct
from employees;#if commission_pct is null then replace with 0
#emphasis '' solves the table name, etc. using keywords
select * from `order`; #order is a keyword
# query constant
select '五斗米',123,employee_id ,last_name
from employees;
# Reality table structure
describe employees ;#describes the details of the fields in the table
desc employees ;
# filter data
#Query the employee information of department 90
select *
from employees
#Filter conditions follow from
where department_id = 90;
#Query the employee information of last_name='King'
select *
from employees
where last_name = 'King';
select last_name
from employees
where last_name like '__a%';
select last_name
from employees
where last_name like '%a%k%' or last_name like '%k%a%';
select * from employees where employee_id  = 100;
select * from employees;
desc employees ;
select last_name,department_id,salary*12 'annual salary'
from employees
order by 'annual salary' desc,last_name asc;
select last_name,salary
from employees
#where salary not between 8000 and 17000
where salary <8000 or salary >17000
order by salary desc
limit 20,20;
select employee_id ,last_name ,email ,department_id
from employees
where email like '%e%'
order by length(email) desc,department_id asc;
#Multiple table query
select employee_id,department_name
from employees,departments
where employees.department_id = departments.department_id ;
#If there are multiple fields that exist in multiple variables in the query statement, you must specify the table where this field is located
select employee_id,department_name,employees.department_id
from employees,departments
where employees.department_id = departments.department_id ;
select *
from job_grades ;
# unequal join
#Query the last name, salary, and grade of employees whose salary is between ~~~
select e.last_name,e.salary,jg.grade_level
from employees e,job_grades jg
where e.salary between jg.lowest_sal and jg.highest_sal ;
#Query employee ID employee name and its manager ID name, self-connection
select e.employee_id 'Employee ID', e.last_name, e2.employee_id 'Manager ID', e2.last_name
from employees e ,employees e2
where e.manager_id = e2.employee_id;
select last_name ,department_name,city
from employees e join departments d
on e.employee_id = d.department_id
join locations l
on d.location_id = l.location_id ;
# left outer join
select last_name,department_name
from employees e left outer join departments d
on e.department_id  = d.department_id ;
#right
select last_name,department_name
from employees e right join departments d
on e.department_id  = d.department_id ;
#Full external connection mysql does not support full
select last_name,department_name
from employees e full join departments d
on e.department_id = d.department_id ;
select e.last_name,d.department_id,d.department_name
from employees e left join departments d
on e.department_id = d.department_id ;
select job_id,location_id
from employees e join departments d
on e.department_id = d.department_id
where d.department_id = 90;
select e.last_name,d.department_name,d.location_id,l.city
from employees e left join departments d
on e.department_id = d.department_id
left join locations l
on d.location_id = l.location_id
where e.commission_pct is not null ;
select last_name,job_id,e.department_id,d.department_name
from employees e join departments d
on e.department_id = d.department_id
join locations l
on d.location_id = l.location_id  
where l.city = 'toronto';
select ceil(32.34)
from dual;
select rand()
from dual;
select sin(radians(30)),degrees(asin(1)),tan(radians(45)),degrees(atan(1))  
from dual;
select pow(2,5),power(2,4),exp(2)
from dual;
select ln(exp(2)),log10(10),log2(2)  
from dual;
select concat(e.last_name,' worked for ',e2.last_name) "details"
from employees e join employees e2
on e.manager_id  = e2.employee_id ;
select concat_ws('-','hello','word')
from dual;
#Strings are indexed from the beginning
select insert ()
Transaction:
Also known as a work unit, it is an operation sequence composed of one or more SQL statements. As a complete work unit, these SQL statements either all execute successfully or all fail to execute. In the database, transactions are used to ensure data consistency
Transaction Processing Language: Transaction Process Language, referred to as TPL, is mainly used to confirm or cancel the operation results of the DML statements that make up the transaction. To confirm is to make the DML operation take effect , which is realized by using the COMMIT command ; to cancel is to make the DML operation invalid , and to be realized by using the ROLLBACK command .
Through the use of transactions, data inconsistency in the database can be prevented. For example, if two bank accounts are transferred, two update operations are involved. These two update operations can only succeed or fail, otherwise the data will be inconsistent.
Atomicity
    A transaction is like an "atom" and cannot be divided. The DML operation statements that make up a transaction either succeed or fail completely. It is impossible to partially succeed and partially fail.
Consistency
    Once the transaction is completed, whether it is successful or failed, the entire system is in a state of data consistency.
Isolation
    The execution of one transaction cannot be interfered with by another transaction. For example, two people withdraw money from an account at the same time, and the correctness of the account balance is ensured through the isolation of transactions.
The isolation level of database transactions is divided into four types: (The following is the problem to be solved, combined with the following case for in-depth understanding)
1. The data modified by Read Uncommited (Read Uncommited) transaction 1 is rolled back by transaction 2
2. Read committed (Read Committed) transaction 1 read information modified by other transactions but not committed
3. Repeatability (Repeatable Read) When transaction 1 performs multiple query operations, the query results are inconsistent
4. Serializable (Serializable) found many more records when querying in the same transaction
Durability
    Also known as permanence, it means that once a transaction is committed, the changes to the data are permanent and cannot be rolled back.
Database optimization:
1. Moderate violation of paradigm
2. Appropriately build index index common index primary key index unique index composite index  
            Avoid too many indexes on frequently updated tables.
            Indexes should be created for frequently used fields.
            It is best not to use indexes for tables with a small amount of data.
            Do not create an index on fields with many identical values ​​(such as the "gender" field). Conversely, indexes can be built on fields with many different values.
3 Divide the table horizontally or vertically. If a table has too much data, it can be split into multiple tables, or a page can split some fields into another table.
4 Select the appropriate database engine InnoDB storage engine supports foreign keys, transactions, and full-text search
Sql statement optimization:
    1 Try to use batch operations
    2 Select the appropriate data type
    3 Large files such as files and pictures are stored in the file system , do not use the database
    4 Use joins (D0IN) instead of subqueries
First of all, it is best to perform comparison operations between fields of the same type , which can avoid the transformation step.
Secondly, try not to use functions to operate on the fields with indexes . The index will be invalid after using the function.
When searching for character fields, we sometimes use the LIKE keyword and wildcards. Although this approach is simple, it also comes at the expense of system performance.
Care should be taken to avoid automatic type conversions by MySQL in queries, because the conversion process can also render indexes ineffective. Heart
5. Database parameter configuration optimization
-- mysql database DBMS
-- Database: It is a container that stores and maintains information specially. Strictly speaking, a database is "a warehouse that organizes, stores and manages information according to the data structure"
-- 1. English word for database: DataBase Abbreviation: DB
-- 2. What database?
# * Warehouse for storing and managing data.
-- 3. Features of the database:
-- 1. Persistent storage of data. In fact, the database is a file system
-- 2. Convenient to store and manage data
-- 3. Use a unified way to operate the database -- SQL
-- 1. What is SQL?
-- Structured Query Language: Structured Query Language
-- In fact, it defines the rules for operating all relational databases. There are differences in the way each database operates, which are called "dialects".
    
-- 2. SQL general syntax
-- 1. SQL statements can be written in one line or multiple lines, and end with a semicolon.
-- 2. Spaces and indentation can be used to enhance the readability of the statement.
-- 3. The SQL statement of the MySQL database is not case-sensitive, and it is recommended to use capital letters for keywords.
-- 4. 3 types of comments
# * Single-line comment: -- comment content or # comment content (mysql specific)
# * Multi-line comment: /* comment */
    
-- 3. SQL classification
-- 1) DDL (Data Definition Language) data definition language
-- Used to define database objects: databases, tables, columns, etc. Keywords: create, drop, alter, etc.
-- 2) DML (Data Manipulation Language) data manipulation language
-- Used to add, delete, and modify data in tables in the database. Keywords: insert, delete, update, etc.
-- 3) DQL (Data Query Language) data query language
-- Used to query the records (data) of tables in the database. Keywords: select, where, etc.
-- 4) DCL (Data Control Language) data control language (understand)
-- Used to define database access rights and security levels, and create users. Keywords: GRANT, REVOKE, etc.
-- query DQL select row projection list join
-- emp (employee table) hiredate entry date deptno department number sal salary mgr manager number comm bonus
-- Note that the codes in the database are collectively referred to as: SQL is case-insensitive
-- There are also keywords in the sql statement to pay attention to
-- Query all data in the table
SELECT * FROM emp;
SELECT empno,ename,sal FROM emp;
SELECT empno employee number, c, job position, sal salary, deptno department FROM emp;
SELECT ename employee name, sal salary, sal*1.2 after salary increase
FROM emp;
SELECT ename employee name, sal*1.2*6+sal*6 annual salary
FROM emp;
-- A null value is an invalid, unassigned, unknown, or unavailable value. NULL is different from zero or blank.
-- The result of any arithmetic expression operation that contains a null value is the null value NULLo
-- IFNULL(comm,0)
SELECT ename employee name, sal salary, IFNULL(comm,0) bonus, (sal*1.2+IFNULL(comm,0))*6+(sal+IFNULL(comm,0))*6 annual salary
FROM emp;
-- Eliminate duplicate rows DISTINCT
SELECT DISTINCT deptno FROM emp;
-- View table structure
DESC emp;
-- Query the employees of 10 departments
SELECT * FROM emp WHERE deptno = 10;
-- When character data is used as the value to be compared, it must be enclosed in single quotes
SELECT * FROM emp WHERE job = 'MANAGER';
-- compare dates
SELECT * FROM emp WHERE hiredate > '1981-05-01';
-- practise
SELECT empno employee number, job position, hiredate entry date
FROM emp
WHERE job = 'SALESMAN';
SELECT ename employee name, hiredate entry date
FROM emp
WHERE hiredate < '1985-12-31';
SELECT empno employee number,ename employee name
FROM emp
WHERE job <> 10;
-- Special comparison operators
-- 1.BETWEEN...AND... (range)
-- 2.IN (collection list) IN(10,20,30)
-- 3. LIKE fuzzy query
-- 4.IS NULL is empty
-- practise
SELECT ename employee name, hiredate entry date
FROM emp
WHERE hiredate BETWEEN '1982-01-01' AND '1985-12-31';
SELECT ename employee name, sal salary
FROM emp
WHERE sal BETWEEN 3000 AND 5000;
SELECT ename employee name, deptno department number
FROM emp
WHERE deptno IN (10,20);
SELECT ename employee name,mgr manager number
FROM emp
WHERE mgr IN(7902,7566,7788);
-- LIKE Use the LIKE operator to determine whether the value to be compared satisfies a partial match, also called fuzzy query
-- %: 0 or any character _: a character @: @_ convert underscore to normal character
SELECT
    *
FROM
    emp
WHERE
    job LIKE 'MAN@_%' ESCAPE '@'
-- practise
SELECT *
FROM emp
WHERE ename LIKE 'W%'
SELECT *
FROM emp
WHERE ename LIKE '%T_'
SELECT ename employee name, comm bonus
FROM EMP
WHERE comm IS NULL
-- Logical operators AND OR NOT
-- Priority NOT > AND > OR
-- practise
SELECT ename employee name, job position, sal salary
FROM emp
WHERE sal > 2000 AND (job = 'MANAGER' OR job = 'SALESMAN')
#job = 'MANAGER' OR 'SALESMAN'
SELECT ename employee name, job position, sal salary
FROM emp
WHERE sal BETWEEN 3000 AND 5000
AND deptno IN (10,20)
SELECT ename employee name, hiredate entry date, job position
FROM emp
WHERE hiredate BETWEEN '1981-01-01' AND '1981-12-31'
AND job NOT LIKE 'SALES%'
SELECT ename employee name, job position, deptno department number
FROM emp
WHERE job IN('SALESMAN','MANAGER')
AND deptno IN(10,20)
AND ename LIKE '%A%'
-- ORDER BY sorting
-- 1. Can be sorted by column name, expression, column alias, and column number of the result set
-- 2.ASC ascending (default) DESC (descending)
-- 3. The ORDER BY clause must be placed at the end
-- .Sorting rules (taking ascending order as an example)
-- Arrange the numbers in ascending order with the small value first and the large value after. That is, they are arranged in numerical order from small to large.
-- ·The dates are arranged in ascending order, the relatively earlier date is in front, and the later date is in the rear.
-- ·Arrange characters in ascending order Arrange the letters in ascending order. That is, it is arranged by Az; Chinese ascending order is arranged according to dictionary order.
-- Null values ​​come first in ascending order and last in descending order.
-- Sort by column name in ascending order
-- Sort by result set number
-- practise
SELECT ename employee name, deptno department number
FROM emp
WHERE deptno IN(20,30)
ORDER BY sal
SELECT ename employee name, deptno department number, sal salary
FROM emp
WHERE sal BETWEEN 2000 AND 3000
AND deptno <> 10
ORDER BY deptno , sal DESC
SELECT ename employee name, hiredate entry date, job position
FROM emp
WHERE hiredate BETWEEN '1981-01-01' AND '1983-12-31'
AND (job LIKE 'SALES%' OR job LIKE 'MAN%')
ORDER BY hiredate DESC
-- Operation
SELECT ename employee name, hiredate entry date, job position
FROM emp
WHERE hiredate > '1982-7-9'
AND job <> 'SALESMAN'
SELECT ename employee name
FROM emp
WHERE ename LIKE '__A%'
SELECT ename employee name, deptno department number
FROM emp
WHERE deptno NOT IN(10,20)
SELECT *
FROM emp
WHERE deptno = 30
ORDER BY sal DESC ,ename
SELECT ename employee name
FROM emp
WHERE mgr IS NULL
SELECT ename employee name, sal salary, deptno department number
FROM emp
WHERE sal > 4500
AND deptno IN(10,20)
-- Multi-table join: what is a join?
-- Connection is to pass certain connection conditions between multiple tables, so that the tables are associated, and then data can be obtained from multiple tables.
-- N tables are connected, at least N-1 connection conditions are required
-- Classification of table joins: writing: 92 writing and 99 writing (left outer join, right outer join)
# divide by condition
#Equivalent connection, non-equivalent connection
#Outer connection, inner connection (connect with itself)
-- Query employee name (EMP), department name (DEPT), work location (DEPT)?
-- DEPT deptno department number dname department number loc work location
-- Equivalent connection first writes the table link, and then writes the connection restriction
SELECT e.ename employee name, d.dname department name, d.loc work location
FROM emp e,dept d
WHERE e.deptno = d.deptno
SELECT * FROM dept
SELECT * FROM emp
-- Cartesian product: all rows in the first table are joined with all rows in the second table
-- Cartesian product condition: the join condition is omitted or the join condition is invalid
SELECT e.ename employee name, d.dname department number, d.loc work location
FROM emp e,dept d
SELECT e.ename employee name, d.dname department number, d.loc work location
FROM emp e,dept d
WHERE e.deptno = e.deptno
SELECT e.ename employee name, d.dname department number, d.loc work location
FROM emp e
JOIN dept d ON e.deptno = d.deptno
-- practise
SELECT e.ename employee name, d.dname department number, d.dname department name
FROM emp e,dept d
WHERE e.deptno = d.deptno
SELECT e.ename employee name, d.loc work place, e.comm bonus
FROM emp e,dept d
WHERE e.deptno = d.deptno
AND d.loc = 'CHICAGO'
AND comm IS NOT NULL
SELECT e.ename employee name, d.loc work location
FROM emp e,  dept d
WHERE e.deptno = d.deptno
AND e.ename LIKE '%A%'
SELECT * FROM salgrade
-- Non-equivalence join
#grade wage grade losal minimum wage hisal maximum wage
SELECT e.ename employee name, sal salary, grade salary grade
FROM emp e,salgrade s
WHERE e.sal
BETWEEN s.losal AND s.hisal
-- Equivalent joins and non-equivalent joins
SELECT e.empno employee number, e.ename employee name, sal salary, grade salary level, d.loc work location
FROM emp e,salgrade s,dept d
WHERE e.sal
BETWEEN s.losal AND s.hisal
AND e.deptno = d.deptno
SELECT e.empno employee number, e.ename employee name, sal salary, grade salary level, d.loc work place
FROM emp e,salgrade s,dept d
WHERE e.sal
BETWEEN s.losal AND s.hisal
AND e.deptno = d.deptno
ORDER BY grade
SELECT e.empno employee number, e.ename employee name, sal salary, grade salary level, d.loc work place
FROM emp e
JOIN salgrade s ON e.sal BETWEEN s.losal AND s.hisal
JOIN dept d ON e.deptno = d.deptno
ORDER BY sal
-- self connection
SELECT e1.empno employee number, e1.ename employee name, e2.ename manager name, e2.empno
FROM emp e1,emp e2,dept d
WHERE e1.mgr = e2.empno
AND e1.deptno = d.deptno
AND d.loc IN ('NEW YORK','CHICAGO')
-- Left outer join: When connecting multiple tables, you can use outer joins to see which rows are not matched according to the join conditions
-- The left outer join takes the left table in the FROM clause as the base table, and all row data in this table will be displayed regardless of whether they match the right table according to the join condition.
SELECT e.ename employee name, d.loc work location
FROM emp e
LEFT OUTER JOIN dept d ON e.deptno = d.deptno
-- practise
SELECT e.ename ,d.dname ,e1.ename
FROM emp e
JOIN dept d ON e.deptno = d.deptno
JOIN emp e1 ON e.mgr = e1.empno
WHERE e.ename = 'SMITH'
-- outer join
SELECT e.ename employee name, dname department name, sal salary, grade salary grade
FROM emp e
JOIN salgrade s ON e.sal BETWEEN s.losal AND s.hisal
JOIN dept d ON e.deptno = d.deptno
WHERE s.grade >= 4
ORDER BY sal
-- group query
#The result returned by the grouping function (aggregate function) is a statement ignoring null values
#MIN() MAX() SUM() AVG() COUNT() Count returns the number of non-empty rows
SELECT MAX(sal),MIN(sal),AVG(sal),SUM(sal),COUNT(empno)
FROM emp
-- First deduplicate and then count
SELECT COUNT(DISTINCT deptno) FROM emp
SELECT AVG(comm) ignores null values
FROM emp
SELECT AVG(IFNULL(comm,0))
FROM emp
SELECT SUM(sal),AVG(sal)
FROM emp
WHERE deptno = 20
SELECT COUNT(*),MAX(sal),MIN(sal)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
WHERE d.loc = 'CHICAGO'
SELECT COUNT(DISTINCT job)
FROM emp
-- group statement
-- GROUP BY child clause
-- All columns in the SELECT list must be included in the GROUP BY clause except for those items of the grouping function.
-- The column specified by GROUP BY does not have to appear in the SELECT list.
SELECT AVG(sal),deptno
GROUP BY deptno
SELECT deptno ,SUM(sal),job
FROM emp
GROUP BY deptno,job
-- practise
SELECT e.deptno,dname,COUNT(empno),MAX(sal),MIN(sal),AVG(sal),SUM(sal)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno
SELECT e.deptno,dname,job,COUNT(empno),MAX(sal),MIN(sal),AVG(sal),SUM(sal)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno,job
SELECT COUNT(*),m.empno,m.ename
FROM emp e
LEFT JOIN emp m ON e.mgr = m.empno
GROUP BY e.mgr
ORDER BY COUNT(e.mgr)
-- HAVING
-- where is not allowed after the grouping clause with having
-- because the where clause cannot compare aggregate functions
SELECT MAX(sal),deptno
FROM emp
GROUP BY deptno
HAVING MAX(sal) > 2900
1. Find the table to be queried through the FROM clause;
2. Use the WHERE clause to perform non-group function screening and judgment;
3. Complete the grouping operation through the GROUP BY clause;
4. Complete the group function screening judgment through the HAVING clause;
5. Select the displayed columns or expressions and group functions through the SELECT clause;
6. Sorting operations are performed through the ORDER BY clause.
-- practise
SELECT e.deptno,dname,count(*)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno
HAVING count(*)>2
SELECT e.deptno,dname,COUNT(*),AVG(sal)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno
HAVING avg(sal) > 2000
AND count(*) > 2
ORDER BY count(*)
-- subquery
SELECT *
FROM emp
WHERE sal > (SELECT sal FROM emp WHERE ename = 'Jones')
SELECT ename
FROM emp
WHERE sal = (SELECT min(sal) FROM emp)
SELECT ename
FROM emp
HAVING min(sal)
-- subquery cannot have null values
--Single-row subquery: returns one column and one row
SELECT ename,job
FROM emp
WHERE sal > (SELECT sal FROM emp WHERE empno = 7876)
AND job = (SELECT job FROM emp WHERE empno = 7369)
SELECT ename,job,sal
FROM emp
HAVING min(sal)
SELECT deptno,min(sal)
FROM emp
GROUP BY deptno
HAVING min(sal)>(SELECT min(sal) FROM emp WHERE deptno = 20)
#Query the name of the employee with the earliest entry date, entry date
SELECT ename,hiredate
FROM emp
HAVING min(hiredate)
#Query the salary and department name of employees whose salary is higher than that of SMITH and whose workplace is in CHICAGO
SELECT e.ename,e.sal,d.dname
FROM emp e
JOIN dept d ON e.deptno = d.deptno
WHERE sal > (SELECT sal FROM emp WHERE ename = 'SMITH')
AND d.loc = 'CHICAGO'
#Query the name of the employee whose entry date is earlier than the employee with the earliest entry date in 20 departments, entry date
SELECT ename,hiredate
FROM emp
WHERE hiredate < (SELECT min(hiredate) FROM emp WHERE deptno = 20)
--
When comparing with multi-row subqueries, multi-row operators need to be used. Multi-row operators include:
IN : collection list
ANY : Indicates that it is compared with any row of results of the subquery, and only one of the conditions is satisfied. ,
    >ANY: greater than minimum
    <ANY: less than max
    =ANY:IN
ALL: Indicates that all rows of the subquery are compared, and each row must satisfy the condition.
    >ALL: greater than all
    <ALL: less than all
    =ALL:
-- not a manager
SELECT ename
FROM emp
WHERE empno NOT IN (SELECT mgr FROM emp WHERE mgr IS NOT NULL)
-- Query the name, salary, department number, and department average salary of employees whose salary is higher than the average salary of their own department
SELECT e.ename,e.sal,e.deptno,a.asl
FROM emp e
JOIN (SELECT avg(sal) asl,deptno FROM emp GROUP BY deptno) a
ON e.deptno = a.deptno
WHERE e.sal > a.asl
-- limit the number of records
LIMIT
x: start index y: number of data entries n: number of pages
x = (n-1) * y
SELECT * FROM emp LIMIT x,y
----------------------------------------------------------------- Tables in the database
Table concept: The table is the most important logical object in the database and the main object for storing data
-- MySQL data type:
Value type: INT FLOAT DOUBLE BIGINT
INT(4) four-digit integer
DOUBLE(7,2) has seven digits, two digits are reserved after the decimal point, and the decimal point occupies two digits
date type:
DATE
DATETIME with hours, minutes and seconds
TIMESTAMP timestamp high precision TIMESTAMP(3) milliseconds TIMESTAMP(6) microseconds
Inserting data and updating data is to use timestamp to record the current time
String:
char fixed length
varchar variable
BLOB binary large object, such as storing a movie, converting it into binary and storing it in blob
tixt large text
ENUM('', ''...) enumeration, select one
-- create table
-- Primary key constraint PRIMARY KEY unique identifier
CREATE TABLE Student(
  stu_id int(4) PRIMARY KEY,
    stu_name VARCHAR(10),
    stu_sex enum('male', 'female'),
    stu_age INT(2) DEFAULT 18, -- default
    stu_birthday DATE,
    stu_school VARCHAR(20),
    stu_subjects INT(4) -- foreign key
)
CREATE TABLE subjects(
  stu_subjects INT(4) PRIMARY KEY,
    sub_name VARCHAR(20) UNIQUE, -- unique
    sub_loc VARCHAR(10) NOT NULL -- not empty
    
)
-- Add foreign keys when creating the table
-- First create the associated subtable
-- Add a foreign key to the main table
CREATE TABLE Student(
  
    stu_subjects INT(4) -- foreign key
    FOREIGN KEY (stu_subjects) REFERENCES subjects(stu_subjects)
)
-- Externally add foreign key constraints
ALTER TABLE student ADD CONSTRAINT FK_student_subjects FOREIGN KEY student(stu_subjects) REFERENCES subjects(stu_subjects)
ADD CONSTRAINT -- add a constraint
REFERENCES -- associations
-- Destroy table
DROP TABLE Student
-- View table structure
DESC student
-- constraints
Self Growth:
auto-increment
Not-null constraint:
NOT NULL
Unique constraint: All row data of the specified column or combination of columns must be unique
UNIQUE
Primary key constraint: the unique identification of each row of the table, and all row data of the specified column or combination of columns must be unique
PRIMARY KEY
Check constraints: MySQL does not support
CHECK
Default constraints:
DEFAULT
Foreign key constraints: the reference table can only be a unique key or a primary key
FOREIGN KEY
--------------------------------------------------------------
-- practise
CREATE TABLE faculties(
  f_id INT(4) PRIMARY KEY,
    f_name VARCHAR(10) UNIQUE,
    f_head VARCHAR(10) NOT NULL,
    f_loc VARCHAR(10) DEFAULT 'Hunnan District'
)
CREATE TABLE class(
  c_id INT(4) PRIMARY KEY,
    c_name VARCHAR(10) UNIQUE,
    f_id INT(4)
)
ALTER TABLE class ADD CONSTRAINT FK_faculties_class FOREIGN
KEY (f_id) REFERENCES faculties(f_id)
CREATE TABLE stu(
    s_id CHAR(10) PRIMARY KEY,
    s_name VARCHAR(20) NOT NULL,
    s_sex CHAR(2),
    s_birthday DATE,
    s_class INT(4)
)
DESC faculties
DESC class
DROP TABLE faculties
DROP TABLE class
DROP TABLE stu
-- copy table
-- excluding data only structure
CREATE TABLE new table name LIKE source table
-- with data
CREATE TABLE new table name SELECT * FROM source table
-- double naming
RENAME TABLE old table name TO new table name
-- Equivalent to
ALTER TABLE old table name RENAME new table name
-- Add a column
ALTER TABLE table name ADD column name data type NOT NULL
-- Change a column
ALTER TABLE table name MODIFY column name data type NOT NULL
-- delete column
ALTER TABLE table name DROP COLUMN column name
-- practise
ALTER TABLE stu ADD gender CHAR(2) DEFAULT '男'
ALTER TABLE stu MODIFY gender char(4)
ALTER TABLE stu MODIFY gender CHAR(4) DEFAULT '女'
ALTER TABLE stu DROP gender
-- constraints
Format: alter table table name add constraint constraint name constraint type (field name)
ALTER TABLE car ADD CONSTRAINT uc UNIQUE (cname)
CREATE TABLE car(
    id INT(10) PRIMARY KEY,
    price DOUBLE(5,2),
    color VARCHAR(6)
)
ALTER TABLE car ADD cname VARCHAR(10)
ALTER TABLE car DROP price
DROP TABLE car
-- view constraints
SHOW INDEX IN table name
-- remove the unique constraint
ALTER TABLE table name DROP INDEX constraint name
-- Remove primary key/foreign key constraints
ALTER TABLE table name DROP PRIMARY KEY constraint name
ALTER TABLE table name DROP FOREIGN KEY constraint name
-- insert data
INSERT INTO car(id,color,cname) VALUE (1001,'black','BMW')
INSERT INTO car VALUE (1002,'blue','Benz')
-- primary key auto-increment
alter table table name change name column name int not null auto_increment
ALTER TABLE table name auto_increment=10 (initial value)
SET auto_increment_increment=10 (increment each time)
-- Inquire
SHOW VARIABLES LIKE '%increment%'
-- change the data
UPDATE table name SET column name 1 = value 1, column 2 = value 2 WHERE condition
The #WHERE clause is used to limit which rows to modify. The SET clause is used to limit which columns are modified.
The update condition in the #WHERE clause is a logical expression that usually requires the use of relational operators
# and logical operators, return True or False.
UPDATE emp SET sal = sal-200 WHERE ename = 'SMITH'
UPDATE emp SET deptno = 20 WHERE empno = 7788
UPDATE emp SET DATE_ADD(hiredate,interval 3 day)
WHERE deptno = 20 AND hiredate > '1982-12-31'
UPDATE emp SET comm = 0 WHERE comm IS NULL
UPDATE emp
SET sal=500+sal
WHERE deptno IN
    (SELECT deptno FROM dept WHERE loc IN ('NEW YORK','CHICAGO'))
UPDATE emp e ,dept d
SET sal=500+sal
WHERE e.deptno = d.deptno AND d.loc IN ('NEW YORK','CHICAGO')
ROLLBACK
-- add the number of days to the specified date
DATE_ADD(hiredate,interval 3 day)
-- delete data delete destroy table drop delete table structure to release space
DELETE FROM table name [WHERE condition]
DELETE FROM emp WHERE mgr = 7566
DELETE FROM emp WHERE deptno =
    (SELECT deptno FROM dept WHERE loc = 'new york')
    
DELETE FROM emp GROUP BY deptno HAVING sal > avg(sal)
-- DELETE FROM emp WHERE empno IN  
-- (SELECT empno FROM
--     (SELECT empno FROM
--         (SELECT avg(sal) avg,deptno FROM emp WHERE deptno IS NOT          NULL GROUP BY deptno) a ,emp e
--     WHERE a.deptno = e.deptno
--     AND sal > avg) eno)
-- Truncate the table between delete and drop to delete data without deleting the table structure to release space
TRUNCATE TABLEtable;
TRUNCATE TABL.Eemp ;
The difference between TRUNCATE and DELETE
-TRUNCATE is DDL, it can only delete all the records in the table, release the storage space, use ROLLBACK can not be rolled back.
- DELETE is DML, which can delete specified records without releasing storage space, and can be rolled back by using ROLLBACK.
-- Views and indexes
View: A view is a logical collection of data from one or more tables. view is not a table
View: view
Table: TABLE
Why use views
-Restrict other users' access to the database table, because the view can selectively display part of the database table
- Easy implementation of complex queries;
- Different views can be generated for the same data;
CREATE VIEW v_emp10
AS SELECT empno,ename,job FROM emp WHERE deptno = 10
DESC v_emp10                    
                                                                    
SELECT * FROM v_emp10                        
                    
-- OR REPLACE
OR REPLACE: If the created view already exists, this option means to modify the definition of the original view
CREATE OR REPLACE VIEW v_emp10
AS SELECT empno,ename,sal,job FROM emp WHERE deptno = 10
DESC v_emp10                
--
Note: Deleting the view data on the view (from a table) will also delete the data of the main table
Delete all views - the main table will not be affected
Deleting the view will not affect the main table
Deleting the data in the view will affect the source table
DROP VIEW name
-- Index: improve database query efficiency INDEX
Type: ordinary index, unique index, full-text index
-- An index is a special database structure that can be used to quickly query specific records in a database table
-- Indexes are an important way to improve database performance. In MySQL, all data types can be indexed
-- How to create an index
Create an index when creating a table
Create indexes on existing tables
Use the ALTER TABLE statement to create indexes
-- Ordinary index, unique index, full-text index
Create table table_1(
Id int(4),
Name varchar(20),
sex boolean,
Index(id)
)
Create table table_2(
Id int PRIMARY KEY,
Name varchar( 20),
Unique index index2_id(id asc)
);
Create table table_3(
Id int,
Info varchar(20),
Full text index index3_info(info)
)engine=myisam;
engine=myisam set the database engine
-- 2. Create an index on an existing table
CREATE [ UNIQUE / FULLTEXT / SPATIAL ] INDEX index name
ON table name(attribute name[(length)][ASC | DESC]);
-- normal index
CREATE INDEX uk_name on table_1 (name(20))
-- unique index
CREATE UNIQUE INDEX uk_name on table_1 (name(20))
-- 3.ALTER TABLE
ALTER TABLE 表名ADD[ UNIQUE |FULLTEXT | SPATIAL ]INDEX
index_name(property_name[(length)][AsC(DESC])
ALTER TABLE table_2 ADD UNIQUE INDEX uk_name (Name (20))
-- delete index
DROP INDEX index name ON table name
DROP INDEX uk_name ON table_2
#Index Design Principles
-- Select a unique index
-- Create indexes for fields that often require sorting, grouping, and union operations
-- Create an index for the fields that are often used as query conditions
-- limit the number of indexes
-- Try to use an index with a small amount of data - try to use a prefix to index
-- Delete indexes that are no longer used or rarely used
-- Database summary
    
---------------------------------------------------------------    
-- practise
CREATE OR REPLACE VIEW v_emps
AS SELECT empno employee number,ename employee name,sal salary FROM emp
WHERE sal BETWEEN 2000 AND 5000 AND ename LIKE '%a%'
SELECT * FROM V_emps
    
CREATE OR REPLACE VIEW v_dsal
AS SELECT dname department name, min(sal) minimum salary, max(sal) maximum salary, avg(sal) average salary
FROM emp e ,dept d
WHERE e.deptno = d.deptno
GROUP BY e.deptno
SELECT * FROM v_dsal
CREATE VIEW V_1 AS
SELECT empno,ename,e.deptno,hiredate
FROM emp e ,dept d
WHERE e.deptno = d.deptno
AND d.loc IN ('new york','chicago')
    
CREATE OR REPLACE VIEW V_2 AS
SELECT e.deptno,dname,min(sal) m
FROM emp e ,dept d
WHERE e.deptno = d.deptno
GROUP BY e.deptno
SELECT e.ename,v.dname
FROM emp e,v_2 v
WHERE e.deptno = v.deptno
AND e.sal = v.m
    
-- practise                                                            
ALTER TABLE salgrade auto_increment=10
SET auto_increment_increment=10
SHOW VARIABLES LIKE '%increment%'
INSERT INTO dept VALUE (50,'HR','SY')
INSERT INTO dept(deptno,dname) VALUE (60,'MARKET')
SELECT * FROM dept
INSERT INTO emp(empno,ename,job,mgr,hiredate,sal) VALUE (8888,'BOB','CLERK',7788,'1985-03-03',3000)
SELECT * FROM emp
CREATE TABLE Manager LIKE emp
INSERT INTO manager
    SELECT *
    FROM emp
    WHERE job = 'MANAGER'
SELECT * FROM manager
CREATE TABLE emp_back
    SELECT *
    FROM emp
    WHERE hiredate < '1982-01-01'
SELECT * FROM emp_back
DROP TABLE emp_back
-- Operation
1. Display the name, department name, and date of entry of employees whose entry date is after 5/1/80
SELECT ename employee name, hiredate entry date, job position
FROM emp
WHERE hiredate > '1980-05-01'
2. Use the left join to query the name of each employee, the name of the manager, and the King without a manager should also be displayed.
SELECT e.ename employee name, m.ename manager name
FROM emp e
LEFT JOIN emp m ON e.mgr = m.empno
3. Use the right connection to query the name of each employee, the name of the manager, and the King without a manager should also be displayed.
SELECT e.ename employee name, m.ename manager name
FROM emp e
RIGHT JOIN emp m ON e.mgr = m.empno
4. Display the names of employees managed by employees KING and FORD and their manager names.
SELECT e.ename employee name, m.ename manager name
FROM emp e
LEFT JOIN emp m ON e.mgr = m.empno
WHERE e.ename = 'KING'
OR m.ename = 'KING'
OR e.ename = 'FORD'
OR m.ename = 'FORD'
5. Display the employee's name, working time, manager's name, and working time. It is required to attend earlier than the manager.
SELECT e.ename employee name, e.hiredate hire date, m.ename manager name, md.hiredate hire date
FROM emp e
LEFT JOIN emp m ON e.mgr = m.empno
JOIN emp md ON e.mgr = md.empno
WHERE e.hiredate < md.hiredate
6. Query the names and average wages of departments whose average salary is more than 2,500 yuan.
SELECT dname department name,avg(sal) average salary
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno
HAVING avg(sal) > 2500
7. Query the name, minimum wage, and maximum wage of departments with more than 2 employees.
SELECT dname department name, MAX(sal) maximum salary, MIN(sal) minimum salary
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno
HAVING COUNT(*)>2
8. Display the manager number and manager name, the minimum salary of the employees managed by this manager, and the KING without a manager should also be displayed, excluding those whose minimum salary is less than 3000, sorted by the minimum salary from high to low
SELECT m.empno manager number, m.ename manager name, MIN(e.sal) minimum salary
FROM emp e
LEFT JOIN emp m ON e.mgr = m.empno
GROUP BY e.mgr
HAVING MIN(e.sal) > 3000
ORDER BY MIN(e.sal) DESC
-- practise
SELECT DISTINCT ename,sal
FROM emp
WHERE empno IN (SELECT mgr FROM emp)
SELECT ename,job,sal
FROM emp
WHERE deptno <> 10
AND sal > ANY (SELECT sal FROM emp WHERE deptno = 10)
SELECT empno,ename,job,sal
FROM emp                                
WHERE deptno <> 20
AND sal > ALL (SELECT sal FROM emp WHERE deptno = 20)
SELECT ename,hiredate
FROM emp
WHERE hiredate >ANY
(SELECT hiredate FROM emp WHERE deptno = 10)
AND deptno <> 10
SELECT ename,hiredate
FROM emp
WHERE hiredate >ALL
(SELECT hiredate FROM emp WHERE deptno = 10)
AND deptno <>10
SELECT ename,job
FROM emp
WHERE job IN
(SELECT job FROM emp WHERE deptno = 10)
AND deptno <> 10
-- Operation
Query the name and average salary of the departments whose average salary is more than 2,500 yuan.
SELECT dname,avg(sal)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno
HAVING avg(sal) > 2500
Query the positions and average wages of employees whose positions do not start with "SA" and whose average salary is more than 2,500 yuan, and sort them in descending order of average salary.
SELECT job,avg(sal)
FROM emp
WHERE job NOT LIKE 'SA%'
GROUP BY job
HAVING avg(sal) > 2500
ORDER BY avg(sal) DESC
Query the department names, minimum wages, and maximum wages of departments with more than 2 employees.
SELECT dname,min(sal),max(sal)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY d.dname
HAVING count(*) > 2
Query the positions that are not SALESMAN, the salary sum is greater than or equal to 2500, and the salary sum of each position.
SELECT job, sum(sal)
FROM emp
WHERE job <> 'SALESMAN'
GROUP BY job
HAVING sum(sal) > 2500
Display the manager number and manager name, the minimum salary of the employees managed by this manager, KING without a manager should also be displayed, excluding those whose minimum salary is less than 3000, sorted by the minimum salary from high to low
SELECT e.ename,m.ename 经理,m.empno,min(e.sal)
FROM emp e
LEFT JOIN emp m ON e.mgr = m.empno
GROUP BY e.mgr
HAVING min(e.sal) > 3000
ORDER BY min(e.sal) DESC
Query the number, name and salary of the employee whose salary is higher than that of employee No. 7782 and who is engaged in the same job as employee No. 7369.
SELECT empno,ename,sal
FROM emp
WHERE sal > (SELECT sal FROM emp WHERE empno = '7782')
AND job = (SELECT job FROM emp WHERE empno = '7369')
Find the names and salaries of the highest paid employees.
SELECT ename,sal
FROM emp
WHERE sal = (SELECT max(sal) FROM emp)
Query the number, name and department minimum wage of the department whose minimum wage is higher than the minimum wage of department No. 10.
SELECT d.deptno,dname,min(e.sal)
FROM emp e
JOIN dept d ON e.deptno = d.deptno
GROUP BY e.deptno
HAVING min(e.sal) > (SELECT min(sal) FROM emp WHERE deptno = 10)
Query the number, name and salary of the employee whose salary is the minimum salary of his department.
SELECT empno,ename,sal
FROM emp
WHERE sal IN (SELECT min(sal) FROM emp GROUP BY deptno)
Display the name and salary of employees whose manager is KING.
SELECT ename,sal
FROM emp
WHERE mgr IN (SELECT empno FROM emp WHERE ename = 'KING')
Display the name, salary, and working hours of employees who started working later than employee SMITH.
SELECT ename,sal,hiredate
FROM emp
WHERE hiredate > (SELECT hiredate FROM emp WHERE ename = 'SMITH')
Create a table empl with the same structure as the emp table, and copy the employee information whose department number is the first 30 to the empl table.
CREATE TABLE emp1 SELECT * FROM emp WHERE deptno = 30
DROP TABLE emp1
1. Find the person with the highest salary in the department
SELECT *
FROM emp
WHERE sal IN (SELECT max(sal) FROM emp GROUP BY deptno)
2. Query the information of employees whose salary ranks between 5 and 10 among all employees
SELECT *
FROM (SELECT * FROM emp ORDER BY sal DESC) sal
LIMIT 4,6
3. Count the number of people and average wages of each job in each department.
SELECT count(job),avg(sal),deptno
FROM emp
GROUP BY deptno,job
4. Query the information of the top 3 employees in salary ranking in department 30
SELECT *
FROM (SELECT * FROM emp WHERE deptno = 30 ORDER BY sal DESC) sal
LIMIT 0,3
5. Information about the department with the largest number of inquiries
SELECT deptno,dname,loc
FROM dept
WHERE deptno =
(SELECT d.deptno
FROM
     (SELECT COUNT(*) cou,deptno
        FROM emp
        GROUP BY deptno
        HAVING cou =
         (SELECT max(c.cou)
            FROM
                (SELECT count(*) cou,deptno
                 FROM emp
                 GROUP BY deptno) c) ) d)
SELECT deptno,dname,loc
FROM dept
WHERE deptno =
(SELECT d.deptno
FROM
     (SELECT COUNT(*) cou,deptno
        FROM emp
        GROUP BY deptno
        HAVING cou >= ALL (SELECT count(*) FROM emp GROUP BY deptno) ) d)
Create a view v_emp_20, which contains the employee number, name, and annual salary column of department No. 20 (annual salary=12*(salary+bonus)
CREATE VIEW v_emp_20 AS(
    SELECT empno,ename,(sal+IFNULL(COMM,0))*12 nsal
    FROM emp
    WHERE deptno = 20
)
Query the information of employees whose annual salary is greater than 10,000 yuan from view v_emp_20;
SELECT * FROM emp
WHERE empno IN (
SELECT empno FROM v_emp_20 WHERE nsal > 10000)
Please create a view for employees whose salary is greater than 2000, which requires displaying the employee's department information, position information, and work location;
CREATE OR REPLACE VIEW v_emp_e AS
SELECT ename,e.deptno,d.dname,d.loc,job
FROM emp e ,dept d
WHERE e.deptno = d.deptno
AND sal > 2000
create table student ( -- student table
    xh char (4),-- student number
    xm varchar (10), -- name
    sex char(2), -- sex
    birthday date, -- date of birth
    sal double(7,2),-- scholarship
    studentcid int(2) -- student's class number
)
Create table class ( -- class table
    classid int (2), -- class number
    cname varchar(20), -- class name
    ccount int (3)-- class number
)
-- 2. Based on the above student table and class table, complete the following questions
-- (1) Add three class information as:
-- 1, JAVA1 class, null
-- 2, JAVA2 class, null
-- 3, JAVA3 class, null
INSERT INTO class VALUE
(1,'JAVA1 class',NULL)
INSERT INTO class VALUE
(2,'JAVA2 class',NULL),
(3,'JAVA3 class',NULL)
-- (2) Add student information as follows: 'A001', 'Zhang San', 'Male', '01-May 05',100,1
INSERT INTO student VALUE ('A001','Zhang San','Male','01-5-05',100,1)
-- (3) Add student information as follows:'AO02','MIKE','Male','1905-05-06',10
INSERT INTO student (xh,xm,sex,birthday,sal)
VALUE ('A002','MIKE','Man','1905-05-06',10)
-- (4) Insert some student information: 'A003', 'JOHN', 'female'
INSERT INTO student (xh,xm,sex)
VALUE ('A003','JOHN','woman')
-- (5) Change the gender of A001 student to 'female'
UPDATE student SET sex = '女' WHERE xh = 'A001'
-- (6) Modify the student information of A001 as follows: gender is male, birthday is set to 1980-04-01
UPDATE student SET sex = '男',birthday = '1980-04-01' WHERE xh = 'A001'
-- (7) Modify the student class whose birthday is empty to Java3 class
UPDATE student SET studentcid = 3 WHERE birthday IS NULL
-- (8) Please use a SQL statement and use a subquery to update the number of people in each class field in the class table
UPDATE class SET ccount =
(SELECT count(*) FROM student WHERE studentcid = 1)
WHERE cname = 'JAVA1班'
UPDATE class a SET a.ccount = (SELECT c.cou FROM
(SELECT count(*) cou,studentcid FROM student WHERE studentcid in (SELECT classid FROM class) GROUP BY studentcid) c
WHERE a.classid=c.studentcid)
-- -------------------------------------------------------------------------------
CREATE TABLE copy_emp(
    empno int(4),
    ename VARCHAR(20),
    hiredate date,
    deptno int(2),
    sal double(8,2)
)
-- 4. On the basis of the third question table, complete the following questions
-- (1) Insert data in the table cop ..emp. It is required to insert a null value in the sal field, the department number is 50, and the working time is January 1, 2000. Other fields are optional
INSERT INTO copy_emp VALUE (1122,'HUILK','2000-01-01',50,NULL)
-- (2) Insert data in the table copy..emp. It is required to insert the employee information of department No. 10 in the emp table
INSERT INTO copy_emp SELECT empno,ename,hiredate,deptno,sal FROM emp WHERE deptno = 10
-- (3) Modify the data in the cop..emp table and require all employees in department 10 to increase their wages by 20%
UPDATE copy_emp SET sal = sal*1.2 WHERE deptno = 10
-- (4) Modify the record that sal is empty in the copy. emp table, and modify the salary to the average salary
UPDATE copy_emp SET sal = (SELECT a.avg FROM (SELECT avg(sal) avg FROM copy_emp) a) WHERE sal IS NULL
-- (5) For employees whose salary is the average salary, modify the salary to be empty
UPDATE copy_emp SET sal = NULL WHERE sal = (SELECT a.avg FROM (SELECT avg(sal) avg FROM copy_emp) a)

Guess you like

Origin blog.csdn.net/weixin_53031149/article/details/127473852