mysql database (single table)

database:

A database is actually a warehouse for storing data. It can store and manage data, and store it on disk according to certain rules.

According to different data types, databases can be divided into

1. Relational database 2. Non-relational database

The mysql database I am currently learning is fast and reliable, free and open source, developed by the Swedish MySQL AB company, and currently belongs to Oracle 's products. MySQL popular relational database management system

The sql language is a visual client tool for connecting to mysql

Syntax specification of mysql:

Case insensitive, keywords are generally capitalized, as well as table names and column names

  Notes:
Single-line comment: #comment text
Single-line comment: -- comment text (with spaces)
Multi-line comments: /* comment text */
DDL (Data Definition Language):
Concept: It is a data (structure) definition language, a language used to create and modify database table structures
Commonly used statements: create, alter, drop, rename
Database Table:
 
The database is composed of tables, put the data in the table, and then put the table in the library
1. Data sheet
A table is the most common and simplest form of data storage and is the basic element of a relational database.
In its simplest form, a table consists of rows and columns, each containing data. Each table has a header and a body, and the header
Define table and column names. Rows in a table are considered records in a file, and columns in a table are considered fields of those records.
2. Record
A record is also called a row of data, which is a row in a table. In relational database tables, a row of data refers to a complete record.
3. Field
A field is a column in a table that holds specific information about each record. For example, the fields of the customer order form include "order ID", "name", "customer ID", "position", "superior", "region", "shipper", "country" and so on. A column of a data table contains all the information for a particular field.
Features of database storage data:
1 Put the data into the table, and then put the table into the library
There can be multiple tables in a database, and each table has a name to identify itself. Table names are unique.
3 The table has some characteristics, which define how data is stored in the table, similar to the design of "class" in Java.
4 Tables are composed of columns, which we also call fields. All tables are composed of one or more columns, and each column is similar to an "attribute" in java
5 The data in the table is stored in rows, and each row is similar to an "object" in Java
How to create or drop a database
Create a database and set the encoding format
//If there is this database, an error will occur
CREATE DATABASE [if not exists] database name [CHARSET utf8]
delete database
DROP DATABASE database name / [IF EXISTS database name ];
modify character set
ALTER DATABASE database name CHARSET gbk;
Note:  Once the database is created, the database name cannot be modified
How to design the table, what characteristics should the table have:
When creating a table, the table needs to have the following characteristics:
1 What information is stored--table name
2 What information is stored in the table--column name
3 The data type and data length of the fields in the table
4 There are constraints
Column data type:
  The character type  
  char is fixed-length, for example, the defined length is 5, if only 2 characters are stored, it will not be full to 5 characters,
  varchar variable length, for example, 5 characters, if only 2 characters are stored, the actual only station 2 characters
  date type
  date year month day (date)
  datetime year month day hour minute second
  numerical type
  float
  double commonly used, higher precision, it is recommended to use
  TINYINT1
  SMALLINT2
  MEDIUMINT3
  int 4
  bigint 8
  text type text can be stored
What are the constraints:
1 There must be a column value in the primary key constraint
  table, which can uniquely represent a record. There
  can only be one primary key column in the table, and it cannot be repeated, nor can it be empty.
  Mycle also supports the automatic growth of the primary key column (must be an integer type through AUTO_INCREMENT)
2 cannot be empty NOT NULL
3 unique constraint UNIQUE
4 check constraint set conditions, check
5 foreign key constraints (multiple tables)
Note: The primary key will automatically increase AUTO_INCREMENT
Default value DEFAULT default_value
Field comment : comment 'comment
Syntax to create a table:
CREATE TABLE table name ( column name data type [ constraint ] [ default value ] [ comment ], ...)
Set the data in the table:
CREATE TABLE t_user( 

id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,

 number INT(5) NOT NULL, 

stuname VARCHAR(10) NOT NULL, 

age INT(3) 

CHECK(age>18), 

birthday DATE, 

weight DOUBLE, 

opertime datetime, 

CONSTRAINT 约束名 约束规则
How to delete and modify the table name
Delete table, modify table name
delete table
DROP TABLE [if exists ]表名
modify table name
RENAME TABLE old table name TO new table name
copy table structure
CREATE TABLE new table name LIKE copied table name;//It is equivalent to backing up the table data, but this is only backing up the structure of the table.
Data Manipulation Language DML
Make changes to the data in the table
Commonly used sentences:
insert,delete,update
insert: insert statement:
Method 1: INSERT INTO table name ( column 1, column 2..., column n) VALUES ( value 1, value 2..., value n);
Method 2: INSERT INTO table name set column name 1= value 1,... column name n= value n;
Method 3: INSERT INTO table name ( column 1, column 2..., column n) VALUES ( value 1, value 2..., value n), ( value 1, value 2...,
value n);
Method 4: INSERT INTO table name ( column 1, column 2..., column n) query statement ( the number of columns in the query matches the number of inserted columns )
INSERT INTO student(sname,gender,birthday,phone,address,height,reg_time)
               VALUE('李丽','女','2002-10-1','156645645','西安',1.78,NOW())//sql语言中获取当前时间的函数NOW
               //插入了一行记录
  INSERT INTO student(sname,gender,birthday,phone,address,height,reg_time)
               VALUES('李丽1','女','2002-10-1','156645888','西安1',1.68,NOW()),
                     ('李丽2','女','2002-10-1','156645777','西安2',1.68,NOW())
              //插入了多行记录   
INSERT INTO student SET sname='王五',gender="男" //插入了一行只有特定信息的记录,其他值为空                 
                     
  INSERT INTO stu(num,sname,gender,birthday)SELECT num,sname,gender,birthday FROM student 

   //从student表中查询了特定的字段,插入到另一个表中
change the data
UPDATE table name SET column name = 'new value' WHERE condition
UPDATE student SET   address = '成都'  
//将表中的所有的address改为成都
  
  UPDATE student SET   address = '西安'  WHERE num = 1

//将表中指定的num=1这一行记录的address改为西安      
  
  UPDATE student SET   address = '西安',height=1.88  WHERE num = 3  

//将表中指定的num=3这一行记录的address和height分别改为西安 和 1.88
delete data
DELETE FROM table name WHERE condition
TRUNCATE TABLE table name ; empty the entire table
DELETE FROM 表名  --只对表中的数据逐行删除

DROP TABLE 表名 --删除表的结构

TRUNCATE TABLE 表名 --清空整张表的数据,是针对ddl上的操作

DQL (Data Query Language)

Can be queried from one table, or from multiple tables
Basic query: select query list from table
Features: The query list can be: fields in the table, constants, expressions, functions
           The result of the query is a virtual table
Query result processing:
All column query: select * from table
SELECT * FROM student
Specific column query: select result column from table name
SELECT num,sname,gender FROM student
The result query uses arithmetic operators: (+-*/) + can only be used as arithmetic operators
SELECT num,sname,height+1 from stu

算出来的身高比如1.22,结果是2.22


 SELECT num,sname,height+num FROM student


比如num是1,height是1.22,,结果是2.22

-- DISTINCT removes duplicate data, duplicate data refers to the value of each column is the same.
 

  SELECT DISTINCT sname,gender FROM student

Use the function after select:

Single row function: each row of data will be processed
    
    Grouping function/aggregate function/statistical function: convert multiple results into a sum max count
     
     string processing
     logic processing
     date
     arithmetic   

Single line function:

-- length (column name) returns the length of the column in bytes, Chinese 3 bytes 
 

SELECT num,LENGTH(sname) FROM student

-- char_length (column name) length in characters
   

SELECT num,CHAR_LENGTH(sname)sname FROM student

-- concat("","",""....) as 别名
 

 SELECT CONCAT(num,":",sname,":",gender)AS studentInfo FROM student


//合在一块

-- convert to uppercase

SELECT UPPER(sname)FROM student
   SELECT LOWER(sname)FROM student
 -- SUBSTRING(column, start position, interception length)
 
 SELECT num,SUBSTRING(sname,2,2) FROM student

//从第二位开始截取2个

   
   -- instr(column name, search character) returns the position where the specified character first appears in the string
   
SELECT num,INSTR(sname,"i") FROM student


   -- trim(substring from column name) remove the specified substring before and after the column name
   

SELECT TRIM("a" FROM sname) FROM student 


   -- Left (right) fill the specified content to the specified length  

   SELECT LPAD(sname,5,"a"),RPAD(sname,5,"a") FROM student 


   -- replace
 

 SELECT REPLACE(sname,"i","I") FROM student

   
-- Logically process the query results
SELECT num,sname,
     

  (CASE WHEN height>=1.80 THEN '大高个' ELSE '不是大高个' END)height,
       (CASE 
            WHEN height>=1.80 THEN '大高个'
            WHEN height<1.80 AND height>1.60 THEN '中等'
            ELSE '低个子' END)height                                 
      FROM student


  
 -- ifnull(column, default) 

 SELECT num,sname,IFNULL(address,'暂未录入')  FROM student 


 
 -- if (condition, return if the condition is true, return if it is not true)
 
 

SELECT num,sname,IF(height>1.80,'大高个子',"不是大高个")height    FROM student

--round (rounding), ceil (value ) : round up, return the smallest integer >= the parameter,

floor (number ) : round down, return the largest integer <= the parameter

SELECT num,sname,ROUND(height) FROM student 
  SELECT num,sname,FLOOR(height) FROM student 


  -- Truncation (truncating a few digits after the decimal point) will not carry RAND() Randomly generate a random number between 0-1

 SELECT num,sname,TRUNCATE(height,1),RAND() FROM student 

date function
--now() : Return the current system date + time
--curdate() : returns the current system date without time
--curtime() : returns the current time, without the date

SELECT num,sname,NOW(),CURDATE(),CURTIME() FROM student
--You can get the specified part, year, month, day, hour, minute, second
--YEAR ( date column ), MONTH ( date column ), DAY ( date column ),
--HOUR ( date column ), MINUTE ( date column ) SECOND ( date column )
 SELECT num,sname,YEAR(birthday),MONTH(birthday) FROM student


 -- string to date type

 SELECT STR_TO_DATE('2002-1-1',"%Y-%m-%d") FROM student


 -- date to string type 

 SELECT DATE_FORMAT(birthday,"%Y-%m")birthday FROM student  
 
 SELECT DATE_FORMAT(birthday,"%Y")birthday FROM student  


 
 -- Calculate the number of days between two dates, datediff(big,small) : returns the number of days between two dates
 

SELECT DATEDIFF(CURDATE(),birthday) FROM student


 
  Grouping function/aggregation function/statistical function variable one
 -- sum() avg() can only handle columns of numeric type
 -- max() min() count() can handle any data type
 

SELECT SUM(height),AVG(height),MAX(height),MIN(height) FROM student
 
 SELECT COUNT(*) FROM student  //表中有多少行记录
 SELECT COUNT(num) FROM student
 SELECT MAX(sname),MIN(sname) FROM student

grouping function 

Function: used for statistics, also known as aggregation function or statistical function or group function
Classification: sum summation, avg average value, max maximum value, min minimum value, count count
(non empty)
1.sum , avg are generally used to deal with numerical type max , min , count can deal with any type
2. The above grouping functions ignore null values
3. The general use of the count function count ( * ) is used to count the number of rows
4. The fields queried together with the grouping function are required to be the fields after group by
conditional query
Use the WHERE clause to filter out rows that do not meet the conditions, and the WHERE clause follows the FROM clause.
General syntax: select result column from table where condition
Compare
=, != <>, >, <, >=, <=
logic operation
and and or or not
SELECT * FROM student WHERE gender = '男'
SELECT * FROM student WHERE gender != '男'
SELECT * FROM student WHERE gender <> '男'

SELECT * FROM student WHERE gender = '男' AND height>1.7 

SELECT * FROM student WHERE gender = '男' OR height>1.7 

SELECT * FROM student WHERE height = 1.78 OR height=1.88 OR height=1.90
SELECT * FROM student WHERE height IN(1.78,1.88,1.90)
SELECT * FROM student WHERE height NOT IN(1.78,1.88,1.90)

-- is null query value is empty
 

SELECT * FROM student WHERE  address IS NULL


SELECT * FROM student WHERE  address IS NOT NULL

//不为空的

-- height BETWEEN 1.70 AND 1.90
 

SELECT * FROM student WHERE   height BETWEEN 1.70 AND 1.90

SELECT * FROM student WHERE   height>=1.70 AND height<=1.90

-- like %keyword% % matches any character _ matches a character
 

SELECT * FROM student WHERE sname LIKE "张_"
SELECT * FROM student WHERE sname LIKE "%三%"

-- union merges the results of multiple query statements and can remove duplicate data in multiple results. Multiple query result columns are the same

SELECT num FROM student WHERE gender = "男"
 UNION 
SELECT num FROM student 


-- union all simply merges multiple queries, does not remove duplicate data, and displays as many records as there are

SELECT * FROM student WHERE gender = "男"
 UNION  ALL
SELECT * FROM student 

-- By default, sort by primary key from small to large

SELECT * FROM student 

-- order by column asc (ascending) desc (descending)

SELECT * FROM student  ORDER BY reg_time ASC
SELECT * FROM student  ORDER BY reg_time DESC
SELECT * FROM student  ORDER BY height ASC
SELECT * FROM student  WHERE gender = "男" ORDER BY height ASC

SELECT * FROM student   ORDER BY height ASC, reg_time DESC
//如果height存在相同的,那就按照后者进行排序

-- Pagination display data Assuming that each page displays 4 items
 -- limit start position (starting from 0), the number of each query
 

SELECT * FROM student WHERE num>0 ORDER BY num ASC  LIMIT 0,4
SELECT * FROM student WHERE num>0 ORDER BY num ASC  LIMIT 4,4
The filter conditions in the group query are divided into two categories :
                         Data Source Source Location Keyword
Filter before grouping                                          Where in front of the original table group by clause                                 
After grouping, filter the grouped result set                                     after                                     group by having

-- Group query group by grouping condition Divide the data with the same grouping condition into the same group for processing

SELECT gender,COUNT(*),MAX(height),AVG(height) FROM student GROUP BY gender

//前者必须与后者相同,,group by 后面的分组内容必须是表中共有的

-- subquery

SELECT * FROM(SELECT gender,COUNT(*)c FROM student   GROUP BY gender)AS t WHERE t.c>3

//想知道表中男女中谁个数大于3,将一开始查询出来的虚拟表看做一个表对它进行查询操作
这就叫做子查询


-- where is to filter before grouping (raw data in the table), and HAVING to filter the data that has been grouped

SELECT gender,COUNT(*)c FROM student WHERE num>0   GROUP BY gender HAVING c>3

Guess you like

Origin blog.csdn.net/weixin_71243923/article/details/125901324