Review of the database (a)

2020 February 28

Database Overview

  1. Database (DataBase: DB): refers to the long-term storage on the storage device of the computer, organized according to certain rules, it can be a collection of user data or application sharing. (File System) storage, maintenance and management of data collection
  2. Database management system (DataBase Management System, DBMS): refers to a method of operating large-scale software and database management, for the establishment, use and maintenance of the database, the database unified management and control, in order to ensure the security and integrity of the database. Users access the data in the database through the database management systems.

Relational database and database management system

Here Insert Picture Description

Relational database servers, databases and tables

Here Insert Picture Description

SQL

Features:
highly non-procedural, which uses SQL database operation, only that "do it", without specifying "how", the implementation and operation of the access path selection is completed automatically by the DBMS.

classification:

  1. The DDL: data definition language for defining database objects: databases, tables, columns, etc.
  2. DML: Data Manipulation Language, to operation record database table
  3. DQL: data query language used to query log
  4. DCL: Data Control Language, used to define access rights and security levels

DDL

  1. Create a database: CREATE {DATABASE | SCHEMA} [ IF NOT EXISTS] db_name [create_specification [, create_specification] ...]
    Liezi:

    1. Mydb1 create database statement: CREATE DATABASE mydb1;
      Results:Here Insert Picture Description
      Here Insert Picture Description
    2. Gbk created using the database character set mydb3 statement: create database mydb3 character set gbk;
      Results:Here Insert Picture Description
      Here Insert Picture Description
      Here Insert Picture Description
    3. Mydb4 statement creates a database using gbk character set and collation of the band: Create database mydb4 character set gbk COLLATE gbk_chinese_ci;
      Results:Here Insert Picture Description
      Here Insert Picture Description
  2. Check Database: show
    examples:
    1. Display Database statement: show databases;
    Here Insert Picture Description
    2. Display the database create statement:show create database mydb3;
    Here Insert Picture Description

  3. Delete the database: drop database db_name;
    example:
    1.drop database mydb4;
    Here Insert Picture Description
    Here Insert Picture Description

  4. Modify the database: ALTER DATABASE db_name [alter_specification ...]
    example:

    1. alter database mydb3 character set utf8;
      Here Insert Picture Description
  5. Use database:use db_name;

  6. View the database currently in use: select database();

  7. Operation Data Table:
    1. Create a table:
    Create table Table (
    Field Type Field 1,
    Field 2 Field Type,
    Field Field Type 3,
    ...
    );
    common data types:
    int: Integer
    double: float, e.g. double (5 , 2) up to 5, which must have two decimal places, i.e., the maximum value is 999.99;
    char: fixed-length string type; char (10) 'ABC'
    VARCHAR: variable-length string type; varchar (10) ' ABC '
    text: string type; (text data can be saved large)
    BLOB: byte type; (store pictures, video, audio)
    dATE: date type, format: the MM-YYYY-dd;
    time: time type, format as: HH: mm: SS
    timestamp: timestamp type yyyy-mM-dd hh: mm : ss automatically assigned
    datetime: datetime type yyyy-mM-dd hh: mm : ss

    Example:
    Create a table of employees
    Here Insert Picture Description

    代码:
    create table emp(
    id int,
    name varchar(50),
    gender varchar(10),
    birthday date,
    entry_date date,
    job varchar(100),
    salary double,
    resume varchar(200)
    );

    1. View all the tables in the current database: show tables;
    2. View the table Field Information: desc table name;
      Here Insert Picture Description
    3. Add a column in the table: alter table 1 Table Name Field Type Field add;
      Here Insert Picture Description
      1. Modified column in the table: alter table table name modify job (list name) varchar (60) (field properties to be modified);
      2. Delete columns in a table: alter table table name drop a list of names;
      3. Table renamed: rename table table table name to the new name;
      4. Create a View table: SHOW CREATE TABLE table name;
      5. Changes to the table character set gbk: ALTER TABLE table name CHARACTER SET gbk;
      6. The name of a column to modify username: ALTER TABLE table name CHANGE name username varchar (100);
      7. Delete a table: DROP TABLE table name;

DML(*)

Data table is to operate add, delete, change.
ps: in mysql, string type, and date type in either single quotes. 'tom' '2015-09-04', null: null

  1. To query all data in the table:select * from 表名;
  2. Insert: INSERT
    Syntax: INSERT INTO table name (name column 1, column name 2, ...) values (column value 1, the column value 2, ...)
    the number and type of order of the columns names correspond to column values.
    Exercise:
    insert data into the staff table
    Code:
INSERT INTO emp(id,name,gender,birthday,salary,entry_date,resume)
VALUES(1,'zhangsan','female','1990-5-10',10000,'2015-5-5-','good girl');

Here Insert Picture Description
Here Insert Picture Description
Exercise bulk copy:
Code:

INSERT INTO emp VALUES
(4,'zs','m','2015-09-01',10000,'2015-09-01',NULL),
(5,'li','m','2015-09-01',10000,'2015-09-01',NULL),
(6,'ww','m','2015-09-01',10000,'2015-09-01',NULL);
  1. Modification operations UPDATE:
    Grammar: UPADTE table name SET column name 1 = value column 1, column names, column value = 2 column 2 ... WHERE name = value
    Exercise:
    1. All employees salary changed to 5,000 yuan.
    Code: update emp set salary = 5000;
    2. Name to 'zs' employees salary changed to 3,000 yuan.
    Code:update emp set salary = 3000 where name = 'zhangsan';
  2. Deletion DELETE
    syntax: DELETE FROM table WHERE column name = [value]
    Exercise:
    1. Delete the table named 'zhangsan' documentary
    Code: delete from emp where name = 'zhangsan';
    All records 2. Delete the table:
    Code: delete from emp;
    3. Use truncate table to delete recorded.
    Code: TRUNCATE TABLE emp;
    data DELETE to delete the table, the table structure is still; can retrieve deleted data after
    TRUNCATE to delete the table is a direct DROP off, and then create a new table the same.
    Deleted data can not be retrieved. Execute faster than DELETE.

DQL operation

DQL data query language (important)
database execute DQL statement does not change the data, but to a database result set is sent to the client. The query returns a result set is a virtual table.

Search Keyword: SELECT
syntax: SELECT column names FROM table
[WHERE -> GROUP BY -> HAVING- > ORDER BY ]

Syntax:
column name SELECT selection_list / to query /
table name FROM table_list / queried /
the WHERE for condition Condition / line conditions /
the GROUP BY grouping_columns / results grouping /
line condition HAVING condition / packet after /
the ORDER BY sorting_columns / grouping of results /
LIMIT offset_start, row_count / results defined /
exercise:

  1. Underlying query
    1 query all the columns
    Code: select * from stu;
    2. Query specify a list
    of code:select sid,sname,age from stu;
  2. Query Condition
    Condition is given in the WHERE clause of a query in the query, the operator can use the following keywords in the WHERE clause and:
    =, =, <> (! With equivalent =! ), <, <=,>, > =;
    the BETWEEN the aND ...;
    the iN (SET); () with a plurality of values in parentheses
    IS NULL ( represented by a null value ); IS NOT NULL ( represented by a non-null value )
    the aND; and
    oR; or
    the NOT; non
    1. gender query for women, and younger than 50 records
    Code: select * from stu where gender='female' and age<50;
    2. query student number is S_1001, or the name of the record for the liSi
    Code: select * from stu where sid = 'S_1001' or sname = 'liSi';
    3. query student number is S_1001, S_1002, S_1003 records
    Code: select * from stu where sid in ('S_1001','S_1002','S_1003');
    4. query student number is not S_1001, S_1002, S_1003 records
    Code: select * from stu where sid not in ('S_1001','S_1002','S_1003');
    5. query age of null records
    Code: select * from stu where age is NULL;
    6. queries between the ages of 20-40 students record
    the code: select * from stu where age>=20 and age <= 40;
    Code: select * from stu where age between 20 and 40;
    7. query gender non-male student records
    Code: select * from stu where gender = 'female';
    Code: select * from stu where gender != 'male';
    Code: select * from stu where gender <> 'male';
    Code : select * from stu where not gender = 'male';
    Code:select * from stu where gender not in ('male');
    8. query name is not recorded as null students
    Code: select * from stu where sname is not null;
    Code:select * from stu where not sname is null;
  3. Fuzzy query
    when you want to search a student's name contains the letters you need to use a fuzzy queries. Fuzzy queries need to use the keyword LIKE.
    Wildcard:
    _ Any one character
    %: 0 ~ n arbitrary characters
    ' photos%% '_ Double'
    Exercise:
    1. Inquiry Name five students recording-letter
    codes: select * from stu where sname like '_____';
    2 Inquiry Name consists of 5 letters, and fifth letter "i" of student record
    Code: select * from stu where sname like'____i';
    student names to 3. query "z" is recorded at the beginning of
    the code: select * from stu where sname like 'z%';
    4. the query name is the first two letters of "i" student record
    Code: select * from stu where sname like '_i%';
    the name of the query It contains the letter "a" of student records
    Code:select * from stu where sname like '%a%';
  4. Query Control field
    1. Remove duplicates
    removed repeatedly recorded (more than two lines or rows of data in the same series) removing duplicates like, need to use the DISTINCT:
    Exercise:
    Query Gender (using the DISTINCT):
    Code: select distinct gender from stu;
    2. and query operations
    when the two fields are the same numeric type, you can do add operations
    exercise:
    inquiry commission with a monthly salary of employees and
    Here Insert Picture Description
    codes: SELECT *,sal+comm FROM emp2;
    3. to add new column name alias
    exercise:
    inquiry commission with a monthly salary of employees and
    Here Insert Picture Description
    Code: SELECT *,sal+comm as total FROM emp2;
    Code: SELECT *,sal+comm total FROM emp2;(as may be omitted)
    4. IFNULL null filter
    for a more beautiful
    exercise:
    the change in comm null 0
    Code: select *, ifnull from emp2 ( comm, 0);
  5. Column sorting order by name asc (default) desc
    asc is ascending, desc descending order, which is the default asc
    exercise:
    1. Query all student records, by age ascending order
    of code: select * from stu order by age asc;
    2. Query all student records, in descending order by age
    Code : select * from stu order by age desc;
    3. query for all employees, sorted by descending salary, if the salary is the same, ascending order by number
    of code:SELECT * FROM emp2 order by sal desc,empno asc;
  6. Aggregation function sum avg max min count
    aggregation function is used to make longitudinal computing function:
    COUNT (): the number of rows of specified columns is not NULL;
    MAX (): maximum value of the specified column is calculated, if the specified string is Column type, using string sorting operation;
    MIN (): minimum value specified column is calculated, if the specified column is a string type, then the use of string sorting operation;
    the SUM (): calculated value and a specified column, if the column type specified not a numeric type, then the calculation result is 0;
    the AVG (): calculating an average value of the designated column, the column if the specified type is not a numeric type, then the calculation result is 0;
    1. COUNT (): when required may use statistical longitudinal COUNT ( )
    exercise:
    1. query stu number of records in the table:
    Code: select count(*) as cnt from stu;
    2. the number of queries emp2 table commissions:
    Code: select count(comm) as count from emp2 where comm is not null;
    Code: SELECT COUNT(comm) cnt FROM emp2;(if not null calculates)
    3. query table number emp2 salary greater than 2500:
    Code: select count(sal) cnt from emp2 where sal>2500;
    4. the number of monthly statistics and commission total more than $ 2,500:
    Code: select count(*) cnt from emp2 where sal+ifnull(comm,0)>2500;
    5. query commission toll, the number of leadership:
    Code: select count(comm),count(mgr) from emp2;
    2. AVG the sUM and
    use the sum as required in the vertical summation 1. ( ) Function
    2. AVG () function when desired longitudinal averaged
    Exercise:
    1. Search and employee salary:
    Code:select sum(sal) from emp2;
    2. Search and salary employees, as well as all employees and commissions:
    Code: select sum(sal),sum(comm) from emp2;
    3. Search and employee salary + Commission:
    Code: select sum(sal+ifnull(comm,0)) from emp2;
    4. statistical average salary of all employees:
    Code: select avg(sal) from emp2;
    3. max and min
    1. When it is desired to do the most longitudinal using the max () function value
    2. min when required for the minimum longitudinal () function
    exercise:
    1. query maximum and minimum wages:
    Code:select max(sal),min(sal) from emp2;
  7. Grouping queries
    need to use 1. Need grouping query when GROUP BY clause ( where aggregate functions occur simultaneously and column names, must be written after by Group )
    Exercise:
    1. Query each department and department number for each department wages and:
    : Code select deptno,sum(sal) from emp2 group by deptno;
    number 2. query department number for each department and each department:
    Code: select deptno,count(*) from emp2 group by deptno;
    3. query sector number of each sector and each sector wage greater than the number of 1500:
    Code: select deptno,count(*) from emp2 where sal>1500 group by deptno;
    2. the HAVING clause
    practice :
    sector 1. query is greater than the sum of wages and salaries and the number 9000:
    Code: SELECT deptno, SUM(sal) FROM emp2 GROUP BY deptno HAVING SUM(sal) > 9000;
    3. Note: where the difference between HAVING:
    1. HAVING is filtered after the data packet, where the data is filtered prior to the packet.
    2 . HAVING aggregation function may be used later (statistical function), can not use the back where the aggregation function.
    3. WHERE condition of the packet is recorded, if a line record does not meet the conditions of the WHERE clause, then this line will not participate in the group record; while HAVING is bound to the packet data.
  8. Dialect LIMIT
    LIMIT query result for defining the start line, and the number of rows.
    The first argument, starting from the first few lines, and the second parameter is a total of a few lines of investigation
    exercise:
    1. Query 5 rows, starting from the zero line (note, starting from the zero line, ie start line)!
    Code: SELECT * FROM emp2 LIMIT 0, 5;
    2. query 10 rows, starting from row 3 start
    Code: SELECT * FROM emp2 LIMIT 3, 10;
    9. the order of the query keywords related to ( )
    1 order of writing the query: select -> from ----> where - > Group by ----> the HAVING ----> by the order -> limit
    2. query execution order: from -> the WHERE -> Group by -> the HAVING - the SELECT -> the order by ----> limit
    *

Today review on here, If there is error, or a few wrong, please correct me, thank you!

Released nine original articles · won praise 8 · views 390

Guess you like

Origin blog.csdn.net/qq_41816516/article/details/104550860