basic introduction
The database can persist data to the local, structured query.
Three basic nouns:
- DB: database, a container for storing data
- DBMS: database management system, also known as database software or database product, used to create or manage DB
- SQL: Structured query language, the language used to communicate with the database, not unique to a certain database software, but a common language for almost all mainstream database software
The characteristics of database storage data:
-
The data is stored in the table, and then the table is placed in the library
-
There can be multiple tables in a database, and each table has a unique table name to identify itself
-
There are one or more columns in the table, which are also called "fields", which are equivalent to "attributes" in java
-
Each row of data in the table is equivalent to the "object" in java
Classification of SQL language
DML(Data Manipulation Language)
: Data manipulation statements, used to add, delete, modify, query database records, and check data integrity. Including the following SQL statements:
- INSERT: Add data to the database.
- UPDATE: Modify the data in the database.
- DELETE: Delete data in the database.
- SELECT: Select (query) data.
DDL(Data Definition Language)
: Define the structure of the database, such as creating, modifying or deleting database objects, including the following SQL statements:
- CREATE TABLE: Create a database table
- ALTER TABLE: change the table structure, add, delete, modify column length
- DROP TABLE: delete the table
- CREATE INDEX: Create an index on the table
- DROP INDEX: delete index
DCL(Data Control Language)
: Data control statement, used to define the user's access authority and security level. Including the following SQL statements:
-
GRANT: Grant access
-
REVOKE: revoke access
-
COMMIT: Commit transaction processing
-
ROLLBACK: Transaction processing rollback
-
SAVEPOINT: Set save point
-
LOCK: lock a specific part of the database
Basic commands
The first is to download the database, download under the Windows platform: http://dev.mysql.com/downloads/mysql
After downloading and installing, you can-right click on the computer-management-services-start or stop the MySQL service. But I'm a programmer, this way is too low, so you can take a look at these commands:
-
start up:
net start mysql服务名
-
stop:
net stop mysql服务名
-
Login
mysql [-h 主机名 -P 端口号] –u用户名 –p密码
, [] This is optional and used for remote connection. -
drop out
exit
A basic operation process
- Enter mysql, enter in the command line: mysql –uroot –p#### (where #### represents the password)
- View which databases are in mysql: show databases;
-
Use a database: use database name;
-
Create a new database: create database database name
-
View which data tables are in the specified database: show tables;
-
Build a table.
-
View the structure of the table: desc table name
-
Delete table: drop table table name
These are some basic operation commands for databases and tables. Only two screenshots of basic operations are shown. Other operations can be tested by themselves.
Then there are basic operations on the data in the table:
-
View all records in the table: select * from table name;
-
Insert records into the table: insert into table name (list of column names) values (list of values corresponding to the column);
-
Note: insert varchar or date type data to use apostrophe Cause
-
Modify record: update table name set column 1 = column 1 value, column 2 = column 2 value where…
-
Delete record: delete from table name where ….
This is probably the most basic operation, and the detailed operation will be expanded below.
DML statement
The above also basically explained that DML is the basic operation of data (that is, tables).
SELECT statement
Query should be the most frequently used operation. The optimization of the database is basically the optimization of the query.
Basic query
Basic grammar
select 查询列表 from 表名;
. For example: select * from student;
This is to query all the data for the student.
- The query list can be fields, constants, expressions, functions, or multiple
- The query result is a virtual table
Query a single select 字段名 from 表名;
field: . For example: select name,age from student;
only query these two fields.
pay attention:
- The SQL language is not case sensitive.
- SQL can be written in one or more lines
- Keywords cannot be abbreviated or branched
- Each clause should generally be written in separate lines.
- Use indentation to improve the readability of statements.
When querying, you can give an alias to the query column to facilitate the display of data.
Rule: Immediately following the column name, you can also add the keyword'AS' between the column name and the alias. The alias uses double quotation marks so that the alias contains spaces or special characters and is case sensitive.
E.g:select name as studentName,age "studentAge" from student;
Deduplication query, sometimes you can use keywords to deduplicate this data without repeating the data. The syntax is as follows:
select distinct 字段名 from 表名;
Conditional query
Use the WHERE clause to filter out rows that do not meet the conditions. The WHERE clause immediately follows the FROM clause. The syntax is as follows:,
select 查询列表 from 表名 where 筛选条件
for example: (only query employees whose department id is 90)
You can also add other comparison operators:
Simple condition operator:> < = <> != >= <= <=>安全等于
Logical operator: && and || or ! not
If there are multiple conditions, you can use logical operators to connect:
Other comparison operations:
Operator | meaning |
---|---|
BETWEEN ...AND... |
Between two values (including boundaries) |
IN(set) |
Equal to one of the list of values |
LIKE |
Fuzzy query |
IS NULL |
Null value |
Use IS (NOT) NULL to determine the null value, for example:select * from student where name is NULL
Use the BETWEEN operation to display the values in an interval:
Use the IN operation to display the values in the list:
Fuzzy query
Use the LIKE operation to select similar values . The selection criteria can include characters or numbers:
- % Represents zero or more characters (any number of characters).
- _ Represents a character.
As shown in the figure below, if the query name starts with the word S, whatever comes after it will do. Only the beginning with S is required. For example, Ssdg will also be queried.
If the% in the above example is changed to _, it becomes only one character behind.
'%' and'-' can be used at the same time:select * from student where name like %进_
Sort query
Basic syntax:select 查询列表 from 表 where 筛选条件 order by 排序列表 【asc}desc】
- asc: Ascending order, if you don't write the default ascending order. desc: descending order
- Sorted list supports single field, multiple fields, functions, expressions, aliases
- The position of order by is generally placed at the end of the query statement (except for the limit statement)
If DESC is not added at the end, the default is ASC ascending order.
If our field is aliased, we need to use the alias for sorting using this field: (salary*12 expanded by 12 times)
If you use multiple fields to sort, sort according to the order of the ORDER BY list. (That is, according to the sorting written in the front, if there are equal, it will be sorted again according to the following fields)
function
The grouping function acts on a group of data and returns a value for a group of data.
Group function type:
- AVG() average
- COUNT() find the total
- MAX() find the maximum value
- MIN() minimum value
- SUM() sum
YesNumerical dataUsing the AVG and SUM functions, you can use the MIN and MAX functions for == any data type (characters are sorted in a dictionary) ==.
COUNT(*) returns the total number of records in the table, applicable to any data type:
COUNT(expr) returns the total number of records for which expr is not empty.
Group query
You can use the GROUP BY clause to divide the data in the table into several groups, the syntax is as follows:
select 分组函数,分组后的字段
from 表
【where 筛选条件】
group by 分组的字段
【having 分组后的筛选】
【order by 排序列表】
All columns in the SELECT list that are not included in the group function should be included in the GROUP BY clause.
The columns included in the GROUP BY clause do not have to be included in the SELECT list. For example, the department_id in the above example can be omitted in the select, but the result will not include this column.
Group functions cannot be used in the WHERE clause
Use HAVING to filter grouping: (same as where, with different scope)
- The rows have been grouped.
- The group function is used.
- The groups that meet the conditions in the HAVING clause will be displayed.
Multi-table query
Multiple tables can be queried and displayed through joint data, the syntax is as follows:select 字段 from 表1,表2,...;
Descartes assembly is produced under the following conditions: (very low efficiency)
- Omit connection conditions
- Invalid connection condition
- All rows in all tables are connected to each other
In order to avoid Cartesian sets, you can add valid connection conditions in WHERE.
- Write the connection conditions in the WHERE clause.
- When there are identical columns in the table, prefix the table name before the column name.
Equivalent connection:
SELECT beauty.id,NAME,boyname FROM beauty ,boys
WHERE beauty.`boyfriend_id`=boys.id;
Distinguish duplicate column names
- Use the table name prefix to distinguish the same columns in multiple tables.
- Columns with the same column names in different tables can be distinguished by table aliases.
- If you use a table alias, you need to use the table alias instead of the table name in the select statement
- Table aliases support up to 32 characters in length, but it is recommended that as few as possible
To connect n tables, at least n-1 connection conditions are required.
Internal connection
Basic grammatical format: (Aliases can be advisable or not)
select 查询列表
from 表1 别名
[inner] join 表2 别名 on 连接条件
where 筛选条件
group by 分组列表
having 分组后的筛选
order by 排序列表
limit 子句;
Features of this link:
- The order of the table can be reversed
- The result of inner join = the intersection of multiple tables
- n table connection requires at least n-1 connection conditions
for example:
#案例.查询名字中包含e的员工名和工种名(添加筛选)
SELECT last_name,job_title
FROM employees e
INNER JOIN jobs j
ON e.`job_id`= j.`job_id`
WHERE e.`last_name` LIKE '%e%';
Outer join
Basic syntax format:
select 查询列表
from 表1 别名
left|right|full [outer] join 表2 别名 on 连接条件
where 筛选条件
group by 分组列表
having 分组后的筛选
order by 排序列表
limit 子句;
Features of this connection:
- The result of the query = all rows in the main table, if the slave table matches it, the matching rows will be displayed, and if the slave table does not match, it will display null
left join
The one on the left is the main table, theright join
one on the right is the main table, andfull join
both sides are the main table- Generally used to query the remaining unmatched rows except for the intersection
Some examples:
#案例1:查询哪个部门没有员工,左外
SELECT d.*,e.employee_id
FROM departments d
LEFT OUTER JOIN employees e
ON d.`department_id` = e.`department_id`
WHERE e.`employee_id` IS NULL;
#右外
SELECT d.*,e.employee_id
FROM employees e
RIGHT OUTER JOIN departments d
ON d.`department_id` = e.`department_id`
WHERE e.`employee_id` IS NULL;
#全外
USE girls;
SELECT b.*,bo.*
FROM beauty b
FULL OUTER JOIN boys bo
ON b.`boyfriend_id` = bo.id;
John connection summary
for example
- Cartesian Product
SELECT * FROM t_dept, t_emp;
There are 20 records in t_dept and 6 records in t_emp. A total of 120 records after the two tables are jointly queried
- Internal connection
SELECT * FROM t_emp a INNER JOIN t_dept b ON a.deptId = b.id;
Only the parts shared by the two tables will be queried
- Left outer join
SELECT * FROM t_emp a LEFT JOIN t_dept b ON a.deptId = b.id;
Take out all the data in the left table, and then query it if the companion data is satisfied, and fill in null if it is not satisfied, which is consistent with the right outer join
- Right outer join
SELECT * FROM t_emp a RIGHT JOIN t_dept b ON a.deptId = b.id;
- Left outer join takes the unique part of the left table
SELECT * FROM t_emp e LEFT JOIN t_dept d ON d.`id` = e.`deptId` WHERE d.id IS NULL
- The right outer join takes the unique part of the right table
SELECT * FROM t_emp a RIGHT JOIN t_dept b ON a.deptId = b.id WHERE a.deptId IS NULL;
Note : When judging whether the field is NULL, you cannot use'='
As = NULL
a result of not being given, but the result is always false . So it must be used IS NULL
to determine the empty
- Full external connection
MySQL does not support full outer joins. To query the complete set of two tables, you need to merge the two query results, so use the UNION keyword
SELECT * FROM t_emp a LEFT JOIN t_dept b ON a.deptId = b.id
UNION
SELECT * FROM t_emp a RIGHT JOIN t_dept b ON a.deptId = b.id;
This kind of connection will get some of the two tables, and then the corresponding ones that are not set to null
- Query the unique content of the two tables
SELECT * FROM t_emp a LEFT JOIN t_dept b ON a.deptId = b.id WHERE b.id IS NULL
UNION
SELECT * FROM t_emp a RIGHT JOIN t_dept b ON a.deptId = b.id WHERE a.deptId IS NULL;
Subqueries and pagination queries
Subquery
The select statement that appears inside other statements is called a subquery or a query that nests other select statements within an inner query, and is called an outer query or a main query
E.g:
select first_name from employees where department_id in(
select department_id from departments where location_id=1700
)
pay attention:
- The subquery should be enclosed in parentheses.
- Place the subquery to the right of the comparison condition.
- Subquery (inner query) is executed one time before the main query
- The result of the subquery is used by the main query (outer query).
For example: whose salary is higher than Abel?
SELECT last_name
FROM employees
WHERE salary > (SELECT salary FROM employees WHERE last_name = 'Abel');
The subquery will be executed first, and then the result will be used by the main query.
Paging query
When there are too many items to be queried and one page is not displayed completely, then you can use paging query.
Basic syntax format:
select 查询列表
from 表
limit [offset,] size;
# 注意:
offset代表的是起始的条目索引,默认从0开始
size代表的是显示的条目数
A fixed paging formula:
If the number of pages to be displayed is page, the number of entries on each page is size:select 查询列表 from 表 limit (page-1)*size,size;
for example:
#案例1:查询前五条员工信息
SELECT * FROM employees LIMIT 0,5;
SELECT * FROM employees LIMIT 5;
#案例2:查询第11条——第25条
SELECT * FROM employees LIMIT 10,15;
Summarize the query and execution order
select 查询列表 7
from 表1 别名 1
连接类型 join 表2 2
on 连接条件 3
where 筛选 4
group by 分组列表 5
having 筛选 6
order by排序列表 8
limit 起始条目索引,条目数; 9
Additions and deletions
insert statement
Basic syntax format:insert into 表名(字段名,...) values(值,...);
pay attention:
-
The type of the value and the type of the field are required to be consistent or compatible
-
The number and order of the fields are not necessarily consistent with the number and order of the fields in the original table, but it must be ensured that the values and the fields correspond one by one
-
If there are fields that can be null in the table, note that null values can be inserted in the following two ways
- Fields and values are omitted
- Write the field, use null for the value
-
The number of fields and values must be the same
-
The field name can be omitted, all columns are defaulted
for example:
INSERT INTO departments(department_id, department_name,manager_id, location_id)
VALUES (70, 'Public Relations', 100, 1700);
If there is a date type: character and date type data should be enclosed in single quotation marks.
INSERT INTO employees(employee_id,last_name,email,hire_date,job_id)
VALUES (300,’Tom’,’[email protected]’,to_date(‘2012-3-21’,’yyyy-mm-dd’),’SA_RAP’);
Syntax for inserting multiple statements at once:insert into 表名【(字段名,..)】 values(值,..),(值,...)
for example:
INSERT INTO departments(department_id, department_name,manager_id, location_id)
VALUES
(70, 'Public Relations', 100, 1700),
(71, 'Public sdf', 23, 65745),
(72, 'Public asdg', 54, 3454);
update statement
Basic syntax format:update 表名 set 字段=值,字段=值 【where 筛选条件】;
You can update multiple pieces of data at once. If you need to roll back data, you need to make sure to set before DML:SET AUTOCOMMIT = FALSE;
Use the WHERE clause to specify the data that needs to be updated:
UPDATE employees SET department_id = 70 WHERE employee_id = 113;
If the WHERE clause is omitted, all data in the table will be updated:
UPDATE copy_emp SET department_id = 110;
delete statement
Basic syntax format:delete from 表名 【where 筛选条件】【limit 条目数】
Use the WHERE clause to delete the specified record:delete from departments where department_name = 'Finance';
If the WHERE clause is omitted, all data in the table will be deleted:DELETE FROM copy_emp;
DDL statement
This part is much less than the above content.
Database management
Create a database:create database [if not exists] 库名 [character set 字符集名];
Modify the library:alter database 库名 character set 字符集名;
Delete library:drop database [if exists] 库名;
Related other commands, this is generally used in the command line:
- show databases; view all current databases
- use employees; "use" a database to make it the current database
Table management statement
Create a table:
create table 【if not exists】 表名(
字段名 字段类型 【约束】,
字段名 字段类型 【约束】,
。。。
字段名 字段类型 【约束】
)
# 举个例子:
CREATE TABLE dept(
deptno INT(2),
dname VARCHAR(14),
loc VARCHAR(13)
);
Commonly used data types:
INT | Use 4 bytes to store integer data |
---|---|
CHAR(size) | Fixed-length character data. If not specified, the default is 1 character, and the maximum length is 255 |
VARCHAR(size) | Variable-length character data is stored according to the actual length of the string, and the length must be specified |
FLOAT(M,D) | Single precision, M=integer place+decimal place, D=decimal place. D<=M<=255,0<=D<=30, default M+D<=6 |
DOUBLE(M,D) | Double precision. D<=M<=255,0<=D<=30, default M+D<=15 |
DATE | Date type data, format'YYYY-MM-DD' |
BLOB | Long text data in binary form, up to 4G |
TEXT | Long text data, up to 4G |
Statement to modify the table:
-
Add column:
alter table 表名 add column 列名 类型 [first|after 字段名];
-
Modify the type or constraint of the column:
alter table 表名 modify column 列名 新类型 [新约束];
-
Modify column name:
alter table 表名 change column 旧列名 新列名 类型;
-
Delete column:
alter table 表名 drop column 列名;
-
Modify the table name:
alter table 表名 rename [to] 新表名;
-
Delete table:
drop table [if exists] 表名;
Common constraints when building tables
NOT NULL
: Not empty, the value of this field is requiredUNIQUE
: Unique, the value of this field cannot be repeatedDEFAULT
: By default, the value of this field does not need to be manually inserted with a default valueCHECK
: Check, mysql does not supportPRIMARY KEY
: Primary key, the value of this field cannot be repeated and is not unique+not nullFOREIGN KEY
: Foreign key, the value of this field refers to the field of another table
Primary key: a table has at most one primary key, and the primary key inherently contains two constraints: unique and non-empty
The role and attention of foreign keys:
- Used to limit the relationship between two tables, the field value of the slave table refers to a field value of the main table
- The foreign key column and the referenced column of the main table require the same type, the same meaning, and no requirement for the name
- The referenced column of the main table requires a key (usually the primary key)
- Insert data, first insert the main table
- Delete data, first delete from the table
create table 表名(
字段名 字段类型 not null,#非空
字段名 字段类型 primary key,#主键
字段名 字段类型 unique,#唯一
字段名 字段类型 default 值,#默认
constraint 约束名 foreign key(字段名) references 主表(被引用列)
)
After a data table is built, these constraints can also be modified or deleted through SQL statements:
- Add non-empty:
alter table 表名 modify column 字段名 字段类型 not null;
- Delete non-empty:
alter table 表名 modify column 字段名 字段类型 ;
- Add default:
alter table 表名 modify column 字段名 字段类型 default 值;
- Delete the default:
alter table 表名 modify column 字段名 字段类型 ;
- Add primary key:
alter table 表名 add [constraint 约束名] primary key(字段名);
- Delete the primary key:
alter table 表名 drop primary key;
For more writing, just search by yourself.
The field value of refers to a field value of the main table
- The foreign key column and the referenced column of the main table require the same type, the same meaning, and no requirement for the name
- The referenced column of the main table requires a key (usually the primary key)
- Insert data, first insert the main table
- Delete data, first delete from the table
create table 表名(
字段名 字段类型 not null,#非空
字段名 字段类型 primary key,#主键
字段名 字段类型 unique,#唯一
字段名 字段类型 default 值,#默认
constraint 约束名 foreign key(字段名) references 主表(被引用列)
)
After a data table is built, these constraints can also be modified or deleted through SQL statements:
- Add non-empty:
alter table 表名 modify column 字段名 字段类型 not null;
- Delete non-empty:
alter table 表名 modify column 字段名 字段类型 ;
- Add default:
alter table 表名 modify column 字段名 字段类型 default 值;
- Delete the default:
alter table 表名 modify column 字段名 字段类型 ;
- Add primary key:
alter table 表名 add [constraint 约束名] primary key(字段名);
- Delete the primary key:
alter table 表名 drop primary key;
For more writing, just search by yourself.