Database knowledge points + SQL statement addition, deletion and modification query (detailed explanation)

# Database related SQL

1. Query all databases

- Format: show databases;        

2.Create database

- Format: create database database name charset=utf8/gbk;

- Example:

- create database db1;

- create database db2 charset=utf8;

- create database db3 charset=gbk;

- show databases;   

3. View database information

- Format: show create database database name;

- Example:

- show create database db1;

- show create database db2;

- show create database db3;

4. Delete database

- Format: drop database database name;

- Example:

- drop database db2;

- drop database db3;

5. Use a database

- A certain database must be used before executing table-related and data-related SQL statements, otherwise an error will be reported.

- Format: use database name;

- Example:

- use db1;

  

# [practise]()

create database +database name charset=utf8/gbk

drop database + database name 

increase

insert into + database name (table field 1, table field 2) values ​​(value 1, value 2) 

insert into + database name values ​​(value 1, value 2) 

delete

delete from +table name where +condition

change

update + table name set value where condition

check

select field information from + table name where condition


**[模糊查询]**
%: 代表0或多个未知字符
    _:代表1个未知字符
        举例:以x开头       x%
            以x结尾       %x
            包含x           %x%
            第二个字符是x       _x%
            以x开头以y结尾    x%y
            第三个是x倒数第二个是y       __x%y_
            
查询姓孙的员工信息
    select * from emp where name like "孙%";
查询名字以精结尾的员工姓名
    select name from emp where name like "%精";
查询1号和2号部门中工作以市开头的员工信息
    select * from emp where job like "市%" and dept_id in(1,2);


[in(x,y,z) Query the value of a field equal to multiple values] 
    Use when querying the value of a field equal to multiple values ​​  

     
[between x and y (including x and y)]  


[is null and is not null]
[and and or and not]
    and: equivalent to && in java, Use when multiple conditions need to be met at the same time 
    or: equivalent to || in java, use when multiple conditions meet one         

        
Query the information of employees whose jobs start with city in departments No. 1 and 2
select *from emp where job like "city%" and dept_id in(1,2) ;
 



[distinct deduplication]
Remove duplicate data
Query the different jobs that appear in the employee table select distinct from job emp;
Query which departments’ ids appear in the employee table select distinct dept_id from emp;


[别名] 
select name as "名字" from emp;
select name "名字" from emp;
select name 名字 from emp;
 



*[Sort order by]** [Place after where]
Format: order by field name asc ascending order (default)/desc descending order;


*[Group query group by]**[Replace where]
    You can divide data with the same value in a certain field into a group, and then perform statistical queries in groups.  
    If each or every such keyword appears in the question and the query content is the result of an aggregate function
    Example:
    Query the average salary of each department
        Select dept_id,avg(sal) from emp group by dept_id;
    Query the ID and average salary of the department with the highest average salary < /span>  
        select dept_id,avg(sal)            
            
            

Query the names and salaries of employees whose salary is higher than 2000, sort by salary in descending order
select name,sal from emp where sal>2000 order by sal desc;
 



**[Aggregation function]**
Aggregation functions can be used to perform statistical queries on multiple queried data
What are the statistical methods? < /span>  Sum     select count(*) from emp;     Query the number of people in the employee table count count(*)     select sum( sal) from emp where job="Programmer";     Query the total salary of programmers Sum()     select avg( sal) from emp where dept_id=1;     Query the average salary of department No. 1 average avg() count count Minimum min Maximum max
Average avg













 



**[having keyword]**
Only ordinary field conditions can be written after where, and aggregate function conditions cannot be written.
Specially written after having Aggregation function conditions, and need to be used in conjunction with group by group query, written after group by

Example: Query the average salary of each department, requiring the average salary to be greater than 2000
    select dept_id,avg(sal) from emp group by dept_id having avg(sal)>2000;
    select dept_id,avg(sal) a from emp group by dept_id having a>2000; <Give an alias to the average salary>
    Query each job The number of people, only query the number of people greater than 1 
    select job,count(*) c from emp group by job having c>1;
    Query the number of each department For the total salary, only employees with leaders are queried, and the total salary is required to be greater than 5400.
    select dept_id,sum(sal) s from emp where manager is not null group by dept_id having s>5400;< /span>     select dept_id,avg( sal) a from emp where sal between 1000 and 3000 group by dept_id having a>=2000;
    Query the average salary of each department, only query the salary between 1000 and 3000, and filter out the average salary below 2000

    
 



**[Paging query]**
Format: limit number of items to skip, number of items requested (number of items per page)
    Number of skipped items = (number of requested pages-1)*number of items per page
    Example: Query 5 pieces of data on the first page (1-5) limit 0,5 < /span>           Query 8 pieces of data on page 7 limit 48,8         Query 10 pieces of data on page 8 limit 70,10         Query 5 pieces of data on page 5 limit 20,5
        Query 5 pieces of data (6-10) on page 2 limit 5,5



1. Query the information of the three people with the lowest salary
select * from emp order by sal limit 0,3;
2. Query the person with the highest salary Employee information
select * from emp order by sal limit 0,1;
3. Query the 3 data on page 2 sorted by joining date
select *from emp order by hiredate limit 3,3;
 



**[Subquery][also known as nested query]
You can use the result of one SQL statement query as the value of another SQL statement condition 

Query employee information whose salary is greater than the average salary of department No. 2
    select avg(sal) from emp where dept_id=2;
    select * from emp where sal>(select avg(sal) from emp where dept_id=2);

Query employee information whose salary is higher than the maximum salary of programmers
    select max(sal) from emp where job="Programmer";
    select * from emp where sal>(select max(sal) from emp where job="Programmer");

Query Sun Wukong’s department information (using dept department table)
    select dept_id from emp where name="Sun Wukong";
    select * from dept where id=(select dept_id from emp where name="Sun Wukong");



**[Associated Query]
1.[Equal Query] select * from A,B where associated relationship and other conditions  

2. [Inner join] format: select * from A join B on association relationship where condition


Query the name of each employee and the corresponding department name  
select e.name,d.name from emp e,dept d where e.dept_id=d.id;

3.[External connection] Query the name, salary and department information of employees whose salary is higher than 2000
select e.name,e.sal,d.* from emp e,dept d where e.dept_id=d.id and sal>2000;



/**String concatenation*/
concat(str1, str2,…) function
Connect multiple strings to form a longer string string

concat_ws(separator, str1, str2, …) function
This function can specify the separator at one time
    
*Details on how to splice SQL strings*
Answer: ①CONCAT() Basic string concatenation type: SELECT CONCAT (lastname, firstname) AS student_name FROM kalacloud_student;
②2. Use spaces to concatenate strings: still When using the SELECT CONCAT() command, spaces need to be enclosed in ' ' two single quotes. SELECT CONCAT(firstname, ' ', Subject) AS StudentDetail FROM kalacloud_student;
③Use special symbols to splice strings: SELECT CONCAT(firstname, '- 39;, subject, '-', qualification) AS Detail FROM kalacloud_student;
④Concatenate strings in the filter query and display it in the table: SELECT CONCAT(qualification , ' ', firstname, ' - ', subject) AS candidate information, wechat_id, phone FROM kalacloud_student WHERE qualification = 'MPhil';
/**⑤Concatenation of strings and Chinese text: SELECT CONCAT('Candidate:', lastname,firstname, ' Subject:',subject,& #39; Education: ', qualification) AS Resume FROM kalacloud_student ORDER BY qualification DESC;*/⑥CONCAT_WS() You only need to write the delimiter once to splice all strings: SELECT CONCAT_WS(' / ' ;, firstname, phone, subject, qualification) AS Detail FROM kalacloud_student;
⑦Summary: The CONCAT() string splicing function is used very frequently in daily work scenarios, but its principle is easy to understand . Any string that is not in the database can be enclosed in ' single quotes.
```

#Special query method

### 1. Related queries (related queries include: equivalent links, inner joins and outer joins)

​​[The query method of querying data from multiple tables at the same time is called associated query]()

- If you are querying data in multiple tables, use related queries: (equivalent links, inner joins and outer joins)

- If you are querying the intersection data of multiple tables, use equivalent links or inner joins (recommended)

- If you are querying the intersection data of all one table and other tables, use outer joins.


### 2. Equivalent link of related query

- Format: select * from A,B where relationships and other conditions

1. Query the name of each employee and the corresponding department name  

select e.name,d.name

from emp e,dept d where e.dept_id=d.id;

1. Query the name, salary and department information of employees whose salary is higher than 2000

select e.name,e.sal,d.* 

from emp e,dept d where e.dept_id=d.id and sal>2000;


### 3. Connection within associated query 

- Inner joins have the same effect as equivalent links. What is queried is the intersection data of the two tables, and data other than the intersection cannot be queried.

insert into emp(name,sal) values("Thanos",5);

- Format: select * from A join B on association relationship where condition

1. Query the name of each employee and the corresponding department name  

select e.name,d.name

from emp e join dept d on e.dept_id=d.id;

1. Query the name, salary and department information of employees whose salary is higher than 2000

select e.name,sal,d.*

from emp e join dept d on e.dept_id=d.id

where sal>2000;


### 4.Outer connection

- Function: Query all the intersection data of one table and another table

- Format: select * from A left/right join B on association relationship where condition;

1. Query all employee names and corresponding department names

select e.name,d.name

from emp e left join dept d on e.dept_id=d.id;

1. Query all department names, locations and corresponding employee names and salaries, and only query employees with leaders

select d.name,loc,e.name,sal

from emp e right join dept d on dept_id=d.id where e.manager is not null;

type of data 

**5数据类型**  

1). 整数: int(m) 和 bigint(m) , bigint等效java中的long,  m代表显示长度,举例m=5,存18  查询到 00018   , 需要补零的话必须使用zerofill关键字             
create table t1(age int(5) zerofill);
insert into t1 values(18);
select * from t1;

2). 浮点数: double(m,d)  m代表总长度,d代表小数长度   54.432  m=5 d=3   
create table t2(price double(5,3));
insert into t2 values(45.2312312123);
insert into t2 values(455.231);   //报错 

3). 字符串
- char(m): 固定长度字符串 , m=5  存abc  占5个字符长度 , 应用场景: 当存储长度固定时,比如存储性别char(1)  , 最大字符长度255
- varchar(m):可变长度字符串, m=5 存abc 占3个字符长度, 最大值65535但是建议保存255以内长度的数据
- text(m):可变长度字符串, 最大值65535 建议保存长度大于255的数据

4). 日期
- date: 只能保存年月日
- time: 只能保存时分秒
- datetime: 保存年月日时分秒, 最大值9999-12-31, 默认值为null
- timestamp(时间戳:保存1970年1月1日到现在的毫秒数):保存年月日时分秒, 最大值2038-1-19 , 默认值为当前系统时间(当赋值为null时触发默认值)
举例:
create table t_date(t1 date,t2 time,t3 datetime,t4 timestamp);
insert into t_date values("2022-06-09",null,null,null);
insert into t_date values(null,"16:16:20","2011-11-22 10:20:30",null);
select * from t_date;

 Database related matters

**1.数据库里索引的作用**
    优点:主要作用为了增加数据的查询速度
    缺点:一是增加了数据库的存储空间,二是在插入和修改数据时要花费较多的时间(因为索引也要随之变动)。    
       
下不适合加索引:
1):如果每次都需要取到所有表记录,无论如何都必须进行全表扫描了,那么是否加索引也没有意义了。
2)、对非唯一的字段,例如“性别”这种大量重复值的字段,增加索引也没有什么意义。    
3)、对于记录比较少的表,增加索引不会带来速度的优化反而浪费了存储空间

**2.什么是数据库的事务**
    事务就是为了保证原有事物的完整性和一致性,通过一定的条件规定该事物的可靠性和安全性(如数据库中的事物)。

事务的四大特性:
A:原子性:一个事物是不可再分的工作单位,该事物要么成功要么失败。
B:一致性:事物必须是使数据库从另外一个一致性状态到另一个一致性状态,与原子性密切相关。
C:持久性:指一个事物一旦提交后对数据库中数据的改变应该是永久不变的。
D:隔离性:一个事物的执行不能够被其他事物所干扰。
    
    
**3.数据库里的字段约束有哪些,各有什么作用** 
    1).主键约束:实现实体的完整性(PK:主键),值唯一,不能为空,且可以自动递增
    3).非空约束:(NOT NULL)保证该字段的内容不能为空null
    4).唯一约束:列表的唯一性约束(UNIQUE)
    5).检查约束:检查列的值是否满足一个boolean表达式(CHECK)
    6).默认约束:给指定的字段可以设置默认值,不设置值时使用默认值而不是null
    
**4.数据库优化的方案有哪些**
    (1)查询时,能不用* 就不用,尽量写全字段名。
    (2)索引不是越多越好,每个表控制在6个索引以内。范围where条件的情况下,索引不起作用,比如where value<100
    (3)大部分 情况连接效率远大于子查询
    (4)多用explain 和 profile分析查询语句
    (5)有时候可以1条大的SQL可以分成几个小SQL顺序执行
    (10)尽量避免使用order by
    (9)查看慢查询日志,找出执行时间长的SQL进行优化

Guess you like

Origin blog.csdn.net/m0_71202849/article/details/126631107