Basic knowledge of MySQL entry and introductory exercise cases

      This blog is mainly used to introduce some basic knowledge of MySQL, and provides an exercise case at the end. I believe that if you can read the whole blog and practice against the case, you can basically master MySQL.

Getting Started with Databases

introduce

Save data to memory:
  Advantages:
     1) Very fast read and write
  Disadvantages:
    1) Data loss due to program shutdown

Saving data to files:
  Advantages:
    1) Data can be permanently saved
  Disadvantages:
    1) Frequent IO operations are not efficient!
    2) Data management is inconvenient. For example, to query a certain data, you need to read it all out and then match it.

Save data to database software:
  Advantages:
    1) Data is permanently saved
    2) Data management is very convenient. (e.g. queries are very fast and convenient)

Data can be said to be the soul of an enterprise! !

What is database software

Database, commonly known as data warehouse. Software (or program) that facilitates the management of data.

Database software on the market

Relational Database

Oracle, a product of Oracle Corporation. Currently the most popular and widely used database software. Compatibility with java language is very good.
Suitable for medium to large, medium to large applications.

SQL Server: is a product of Microsoft Corporation. The window platform is widely used. It is very compatible with c# and net platforms.

DB2: A product of IBM Corporation. IBM Server -> UNIX -> DB2 -> Websphere

MySQL: A product of an open source organization. Products of Oracle Corporation. free! ! ! Compatible with the java language is very good! Suitable for small and medium-sized enterprises, small and medium-sized applications

non-relational database

MongoDB: Non-relational database.


Getting Started with MySQL

1) Go to the mysql official website to download.
2) Install mysql software
3) Use to
verify whether it is successful
Open cmd -> enter mysql -u root -p enter -> enter password and enter

C:\Users\APPle>mysql -u root -p
Enter password: **
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.40 MySQL Community Server (GPL)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the current input statement.

MySQL database

MySQL data storage structure
  first database, then table, and then data

database management

  1. Query all databases
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |     -- mysql元数据,基础数据
| mysql              |     --mysql配置数据库,其中包含用户信息。(用户名和密码,权限管理)
| performance_schema |    --mysql数据库软件的运行数据,日志信息,性能数据
| test               |     --测试数据库。空的
+--------------------+
4 rows in set (0.00 sec)
  2. Create a database
mysql> create database day15       -- 指定默认字符集创建数据库
    -> default character set utf8
    -> ;
Query OK, 1 row affected (0.00 sec)
  3. View the default character set of the database
mysql> show create database day15;
+----------+----------------------------------------------------------------+
| Database | Create Database                                                |
+----------+----------------------------------------------------------------+
| day15    | CREATE DATABASE `day15` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+----------------------------------------------------------------+
1 row in set (0.00 sec)
  4. Delete the database
mysql> drop database day15;
Query OK, 0 rows affected (0.01 sec)
  5. Modify the database
mysql> alter database day15 default character set gbk;
Query OK, 1 row affected (0.00 sec)

  table management

select database

  1 View all tables
mysql> show tables;
+-----------------+
| Tables_in_day15 |
+-----------------+
| student         |
+-----------------+
1 row in set (0.00 sec)
  2 Create the table
mysql> create table student(
    -> sid int,
    -> sname varchar(20),
    -> sage int
    -> );
Query OK, 0 rows affected (0.01 sec)
  3 View table structure
mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid   | int(11)     | YES  |     | NULL    |       |
| sname | varchar(20) | YES  |     | NULL    |       |
| sage  | int(11)     | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
  4 delete table
mysql> drop table student;
Query OK, 0 rows affected (0.01 sec)
  5 Modify the table
   1) Add fields
mysql> alter table student add column sgender varchar(2);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0
   2) delete field
mysql> alter table student drop column sgender;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0
   3) Modify the field type
mysql> alter table student modify column remark varchar(100);
Query OK, 0 rows affected (0.07 sec)
Records: 0  Duplicates: 0  Warnings: 0
   4) Modify the field name
mysql> alter table student change column sgender gender varchar(2);
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0
   5) Modify the table name
mysql> alter table student rename to teacher;
Query OK, 0 rows affected (0.01 sec)
  6 Add, delete and modify data
   1.1 Add data

– Insert all fields. must be inserted in order

INSERT INTO student VALUES(1,'张三','男',20);

– Be careful not to have less or more field values

-- INSERT INTO student VALUES(2,'李四','女');

- Insert partial fields

INSERT INTO student(id,NAME) VALUES(2,'李四');
   1.2 Modify data

– Modify all data (recommended to be used sparingly)

UPDATE student SET gender='女';

– Modification with conditions (recommended)

UPDATE student SET gender='男' WHERE id=1; -- 修改id为1的学生,修改性别为男

– Modify multiple fields, note: SET field name=value, field name=value,….

UPDATE student SET gender='男',age=30 WHERE id=2;

– Multi-condition selective modification

update student set mark=(
case nation
when '满族' then mark+5
when '回族' then mark+10
-- 建议必须加这个,不然其他不符合条件会变成null
else mark
end
)
-- 优化,如果没有加where ,会修改所有数据。加了就只会修改满族自己所需条件的条数
where nation='满族' or '回族';
   1.3 Deleting data

– delete all data (recommended to be used sparingly)

DELETE FROM student;

– Conditional delete (recommended)

DELETE FROM student WHERE id=2;

– Another way
– delete from: You can delete the entire table
1) You can delete with conditions
2) Only the data of the table can be deleted, but the constraints of the table cannot be deleted
3) The data deleted by delete from can be rolled back (transaction)
– truncate table : You can delete the entire table
1) Can not delete with conditions
2) You can delete the data of the table, you can also delete the constraints of the table
3) The data deleted using truncate table cannot be rolled back

TRUNCATE TABLE student;
  7 Query data (emphasis)
   1 Query all columns
SELECT * FROM student;
   2 Query the specified column
SELECT id,NAME,gender FROM student;
   3 Add constant columns when querying

– Requirement: Add a class column when querying the student table, the content is "java employment class"

SELECT id,NAME,gender,age,'java就业班' AS '年级'  FROM student;
   4 Merge columns when querying

– Requirement: Query the total score of each student’s servlet and jsp

SELECT id,NAME,(servlet+jsp) AS '总成绩' FROM student;

– Note: Merge columns can only merge fields of numeric type

SELECT id,(NAME+servlet) FROM student;
   5 Remove duplicate records when querying (DISTINCT)

– Demand: Inquire about the gender of the student

SELECT DISTINCT gender FROM student;

- another syntax

SELECT DISTINCT(gender) FROM student;

– Requirement: Check the area where the student is located

SELECT DISTINCT address FROM student;
   6 Conditional query (where)

– 2.7.1 Logical condition: and (and) or (or)
– Requirement: Query the student whose id is 2 and whose name is Li Si

SELECT * FROM student WHERE id=2 AND NAME='李四'; -- 交集

– Requirement: query the student whose id is 2, or whose name is Zhang San

SELECT * FROM student WHERE id=2 OR NAME='张三'; -- 并集

– 2.7.2 Comparison conditions: > < >= <= = <> (not equal to) between and (equivalent to >= and <=)
– Requirement: Query servlet for students whose scores are greater than 70

SELECT * FROM student WHERE servlet>70;

– Requirements: Query students whose JSP scores are greater than or equal to 75 and less than or equal to 90

SELECT * FROM student WHERE jsp>=75 AND jsp<=90;

- another syntax

SELECT * FROM student WHERE jsp BETWEEN 75 AND 90; -- (包前包后)
SELECT * FROM student WHERE gender<>'男';

– 2.7.3 Null condition (null empty string): is null / is not null / =” / <>”
– Requirement: Query students whose address is empty (including null and empty string)
– null vs empty string
– null: means no value
– empty string: has value!
– Judging null

SELECT * FROM student WHERE address IS NULL ;

– Judge empty string

SELECT * FROM student WHERE address='';

SELECT * FROM student WHERE address IS NULL OR address=''; -- (包括null和空字符串)

– Requirement: Query students with addresses (excluding null and empty strings)

SELECT * FROM student WHERE address IS NOT NULL AND address<>'';

– 2.7.4 Fuzzy condition: like
– The following replacement tokens are usually used:
– % : means any number of characters
– _ : means one character
– Requirement: Query students with the last name 'Zhang'

SELECT * FROM student WHERE NAME LIKE '李%';

– Requirement: Query students whose last name is 'Li' and whose name has only two characters

SELECT * FROM student WHERE NAME LIKE '李_';

2.7.5 Inclusion conditions: in
query students whose major numbers are 112, 113, and 114

select * from student where major_no in ('112','113','114');
   7 Aggregate queries (queries using aggregate functions)

– Commonly used aggregation functions: sum() avg() max() min() count()
– Requirement: Query the total score of the student’s servlet (sum(): sum function)

SELECT SUM(servlet) AS 'servlet的总成绩' FROM student;

– Requirement: Query the average score of the student’s servlet

SELECT AVG(servlet) AS 'servlet的平均分' FROM student;

– Requirement: Query the highest score of the current servlet

SELECT MAX(servlet) AS '最高分' FROM student;

– Requirements: Query minimum score

SELECT MIN(servlet) AS '最低分' FROM student;

– Requirement: Count how many students there are currently (count(field))

SELECT COUNT(*) FROM student;

SELECT COUNT(id) FROM student;

– Note: The number counted by the count() function does not contain null data
– Use count to count the number of records in the table, use fields that do not contain null values

SELECT COUNT(age) FROM student;
   8 Paging query (limit start line, query several lines)

– The starting line starts from 0
– Paging: how many lines are displayed on each page
of the current page – sql for querying the data of the current page by paging: SELECT * FROM student LIMIT (current page-1) * how many lines are displayed on each page, how many lines are displayed on each page ;

– Requirement: Query records 1 and 2 (data on page 1)

SELECT * FROM student LIMIT 0,2;

– Query records 3 and 4 (data on page 2)

SELECT * FROM student LIMIT 2,2;

– Query records 5 and 6 (data on page 3)

SELECT * FROM student LIMIT 4,2;

– Query the 7th and 8th records (no records will not be displayed)

SELECT * FROM student LIMIT 6,2;
   7.9 Query order (order by)

– Syntax: order by field asc/desc
– asc: order, positive order. Numeric: Ascending, Alphabet: Natural order (az)
– desc: Reverse order, reverse order. Numeric: Descending, Alphabet: Natural reverse order (za)

– By default, it is sorted in the order of inserted records

SELECT * FROM student;

– Requirements: Sort by id order

SELECT * FROM student ORDER BY id ASC;
SELECT * FROM student ORDER BY id; -- 默认正序

SELECT * FROM student ORDER BY id DESC;-- 反序

– Note: Multiple sorting conditions
– Requirements: According to the positive order of servlet, according to the reverse order of jsp

SELECT * FROM student ORDER BY servlet ASC,jsp DESC;
   10 Group query

– 2.11 Group by query
– Requirement: Query the number of men and women
– Expected results:
– Male 3
— Female 2
– 1) Group students by gender (GROUP BY gender)
– 2) Count the number of people in each group (COUNT(* ))

SELECT gender,COUNT(*) FROM student GROUP BY gender;
   11 Filter after group query

– Requirement: Query the gender with a total number of more than 2
– 1) Query the number of men and women
– 2) Filter out records with a number of more than 2 (having)
– Note: Use the where keyword for the condition before grouping, and the having keyword for the condition before grouping

SELECT gender,COUNT(*) FROM student WHERE GROUP BY gender HAVING COUNT(*)>2;

Summary one:

mysql foundation
  1) mysql database function: manage data
  2) mysql storage structure:
   database: management database (CRUD)
   table: management table (CRUD)
   data: management data
       addition, deletion and modification:
       query:
       12 kinds of queries (single table query)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325772422&siteId=291194637