Mysql (Linux database or in Navicate)

Mysql database composition

Server: Mainly store data, receive SQL statements sent by users, and return execution results to the client

Client: send the sql statement to be executed by the user, and display the execution result returned by the server

Command line database connection method

mysql -h database IP -P port number -u database login username -p database login password
If -h is not added, it means the machine, -P is not added, which means the default port 3306

type of data

number type

 string type

time and date type

constraint

Command line operation database, table

view all databases         show        database;

use database        

use database name;
View the currently used database select database();
create database create database database name charset=utf8;
delete database drop database database name;
View all tables in the database show tables;
View the structure of the database table desc table name;(desc =describe)
View the creation statement of the data table show create table table name;

Database table operations

1. Create a database table

grammar:

create table table name (

        field name 1 type constraint,

        Field name 2 type constraint

        ... ... ...

)

example:

Create a student table with field requirements: name (length 10), age, height (2 decimal places)

CREATE table students(
	id int UNSIGNED PRIMARY KEY auto_increment,
	name VARCHAR(20),
	height decimal(5,2)
	)

2. Delete the database table

drop table tablename (this command will permanently delete the table and all its data)

drop table if exists students (Check if the table exists before dropping the table. If the table exists, the table will be dropped; if the table does not exist, no error will be raised)

Data addition, deletion, modification and query operations

Increase (insert):

1.1 Add a row of data

insert into table name values(...)

example:

insert into students values(0,'jingbeng',12.66);

//Primary key self-growth can be replaced by 0 or NULL

Another way of writing:

insert into students(name) values('nnn')

1.2 Adding multiple rows of data

Method 1: Write multiple insert statements, separated by " ;"

insert into students(name) value ('jingbeng1');

insert into students(name) value ('jingbeng3');

insert into students values(0,'jingbeng2',23,167.56)

Method 2: Insert multiple pieces of data through one insert statement, and separate the data with ","

Format 1: insert into table name values ​​(...), (...) ...

Example: insert into students values(0,'Arthur 3',23,167.56),(0,'Arthur 4',23,167.56)

Format 2: insert into table name (field name 1,...) value (value 1,...), (value 1,...)...

Example: insert into students(name) value ('Old Master Q 5'),('Old Master Q 6')

2. Check (select):

1.1 Simple query

select * from table name;

Example: select * from students;

1.2 Query some field data

select field 1, field 2... from table name;

例子:select name,sex,age from students;

1.3 alias

Table alias: select alias. field 1, alias. field 2... from table name as alias;

例子:select s.name,s.age from students as s;

Field alias: select field 1 as alias 1, field 2 as alias from table name

例子:select name as n,age as a from students;

1.4 Deduplication of field content

select distinct field from table name;

1.5 Conditional query (where)

select field 1, field 2... from table name where condition;

例: select * from students where id=1;

Description: where supports multiple operators for conditional processing

comparison operation

logic operation

fuzzy query

range query

Empty judgment

1.5.1 Conditional query - comparison operator

Example 1: Query Xiao Qiao's age

select age from students where name='小乔’

Example 2: Query students under the age of 20

select * from students where age<20

Example 3: Query students whose hometown is not in Beijing

select * from students where hometown!='北京'

1.5.2 Conditional query - logical operators

Example 1: Query female students whose age is less than 20

select * from students where age<20 and sex='女'

Example 2: Query female students or students in class '1'

select * from students where sex='女' or class='1班

Example 3: Query non-Tianjin students

select * from students where not hometown='天津'

1.5.3 Condition query - fuzzy query

Keyword: like

% : match any number of characters

- : match any character

Example 1: Query students with the surname Sun

select * from students where name like '孙%'

Example 2: Query students whose surname is Sun and whose first name is one character

select * from students where name like '孙_'

Example 3: Query students whose names end with 'Joe'

select * from students where name like '%乔'

Example 4: Query students whose names contain '白'

select * from students where name like '%白%'

1.5.4 Condition query - range query

in means in a non-contiguous range

Example: Query students whose hometown is Beijing, Shanghai or Guangdong

select * from students where hometown in('Beijing','Shanghai','Guangdong')

between ... and ... means in a continuous range

Example: Query students whose age is 18 to 20

select * from students where age between 18 and 20

1.5.5 Conditional query - empty judgment

Note : Mysql empty means null, which is different from '' (empty).

Judgment is empty : is null

Example: Query students who have not filled in their ID cards

select * from students where card is null

Judgment is not empty : is not null

Example: Query students who have filled in their ID cards

select * from students where card is not null

1.6 Sorting (desc needs to be added in descending order)

Example 1 : Query all student information, sorted by age from youngest to oldest
select * from students order by age;
Example 2 : Query all student information, sort by age from oldest to youngest, if the age is the same, then sort by student number from smallest to largest
select * from students order by age desc,studentNo;

1.7 Aggregate functions

The use of aggregate functions is for the convenience of data statistics

Aggregate functions cannot be used in where:

count(): Query the total number of records

max (field name): query the maximum value

min (field name): query the minimum value

sum (field name): sum

avg (field name): find the average

1.8 grouping (group by)

Group by field, the same data in this field will be put into a group. The purpose of grouping is to count the data of each group ( using aggregation function )

Syntax: select field 1, field 2, aggregate function ... from table name group by field 1, field 2...

1.9 Screening after grouping (having...)

Syntax : select field 1, field 2, aggregation ... from table name group by field 1, field 2, field 3... having conditions

ps: The conditional operator behind the keyword having is the same as where
Example 1 : Query the total number of boys
Option 1 : select count(*) from students where sex=' male '
Option 2 : select sex, count(*) from students group by sex having sex=' male '

Comparison between having and where:

where is to filter the data of the table specified after from, which belongs to the filtering of original data.

Having is to filter the results of group by .

Aggregate functions can be used in the condition after having, but not after where .

1.10 Pagination - get some data

Syntax: select * from table name limit start count

start indicates the starting position, and the index starts from 0 by default

count means to get count pieces of data from the start position

Example: Get the information of rows 2-4 of the student table

select * from students limit 1,3;

1.10.1 Page display

Paging query: select * from students limit (n-1)*m,m

Description: n indicates which page of data is displayed; m indicates how many pieces of data are displayed on each page

1.11 Connection query

Inner join (inner join...on...)

grammar:

select * from table 1 inner join table 2 on table 1. column = table 2. column;

select * from table 1, table 2 where table 1. column = table 2, column;

Example 1 : Query student information and student grades
方式一 : Select * from students stu inner join scores sc on stu.studentNo = sc.studentNo
方式二 :select * from students stu, scores sc where stu.studentNo = sc.studentNo
Example 2 : Query course information and course grades
select * from courses cs inner join scores sc on cs.courseNo = sc.courseNo
Example 3 : Query Wang Zhaojun's grades, request to display name, course number, grades
select stu.name, sc.courseNo, sc.score from students stu
inner join scores sc on stu.studentNo = sc.studentNo where
Example 4: Query student information and grades corresponding to students' courses
SELECT * FROM students stu INNER JOIN scores sc on stu.studentNo=sc.studentno INNER JOIN  courses cs on sc.courseNo=cs.courseNo;
Example 5: Query Wang Zhaojun's database grades, requesting to display name, course name, grades
SELECT stu. name ,cs. name ,sc.score FROM students stu INNER JOIN scores sc on
stu.studentNo=sc.studentno INNER JOIN courses cs on sc.courseNo=cs.courseNo WHERE
stu.name =' Wang Zhaojun ' and cs.name = ' database ';
Example 6: Query the highest score among boys, and require display of name, course name, and score
SELECT stu.NAME,sc.score,cs.NAME FROM students stu INNER JOIN scores sc on
stu.studentNo=sc.studentno INNER JOIN courses cs on cs.courseNo=sc.courseNo
WHERE stu.sex=' man '
ORDER BY sc.score DESC
LIMIT 0,1;

Left join (left join...on...)

Definition: (right join and vice versa)

  • A left join selects all rows from the left table (the table on the left) and includes matching rows from the right table (the table on the right) that meet the join condition.
  • If a row in the left table does not have a matching row in the right table, the result set will show that the value of the corresponding column in the right table is NULL.
  • All rows from the left table will be included in the result set, while rows from the right table that do not meet the join criteria will be excluded

Syntax: select * from Table 1 left join Table 2 on Table 1. Column = Table 2. Column

Example 1: Query the grades of all students, including those without grades
select * from students stu
left join scores sc on stu.studentNo = sc.studentNo Example 2: To query the scores of all students, including those without scores, the course name needs to be displayed
select * from students stu
left join scores sc on stu.studentNo = sc.studentNo
left join courses cs on cs.courseNo = sc.courseNo

right join

Syntax : select * from table 1 right join table 2 on table 1. column = table 2. column
Example 1: Query the grades of all students, including those without grades
select * from scores sc
right join students stu on stu.studentNo = sc.studentNo
Example 2: To query the grades of all students, including students without grades, the course name needs to be displayed
select * from scores sc
right join courses cs on cs.courseNo = sc.courseNo
right join students stu on stu.studentNo = sc.studentNo

ps: In the left and right joins, whoever is left (right) and which longest table is placed on the left (right) side

1.14 Subqueries

act as a condition

Example 1 : Query Wang Zhaojun's grades and request to display the grades (scalar query)
select * from scores where studentNo = ( select studentNo from students where name = ' 王昭君 ' )
Example 2: Query the grades of 18 -year-old students and request to display the grades (column subquery)
select * from scores where studentNo in ( select studentNo from students where age= 18 )
Example 3: Query the information of students in the same class and age as Wang Zhaojun (row subquery)
select * from students where ( class ,age)=( select class ,age from students where name = ' 王昭君 ' )

act as a data source

Example 1: Query database and course grades of system tests
Select * from scores s inner join ( select * from courses where name in ( ' 数据库
' , ' System Test ' )) c on s.courseNo = c.courseNo

change (update)

Syntax: update table name set field name 1= new value 1, field name 2= new value 2...where condition

Example : Modify the student data whose id is 5 , change the name to Di Renjie, and change the age to 20
update students set name=' 狄仁杰 ',age=20 where id=5

delete

Syntax: delete from table name where condition;

Example : Delete the student data whose id is 6
delete from students where id=6
Note : This method is physical deletion, and most of the work uses logical deletion.
Logical deletion refers to setting a field to indicate that the current record has been deleted.
is_delete field to identify, 1 means deleted, 0 means not deleted.
ps: When delete deletes all data, the self-growth field will not start from 1

Other ways to delete data (truncate/drop)

truncate table table name
Example : Delete all data in the student table ( retain the table structure )
truncate table students
drop table table name
Delete the student table ( including all data and table structure )
drop table students

Guess you like

Origin blog.csdn.net/weixin_53328532/article/details/131361935