1. Basic grammar of database

SQL statement


Preface

Whether you are developing a web application or an app, you need a database to store your business data. It can be said that as a Java program developer is inseparable from the interaction with the database. The database used this time is MySQL, and the server is Navicat


One, create a database

(1) Use SQL statement to create: create database csdn
(2) Switch database command: use csdn
(3) Delete database SQL statement: drop database csdn

Two, data sheet

1. Create a table

//名   类型  不为空(NOT NULL) 主键(PRIMARY KEY)自增(auto_increment)
CREATE TABLE tb_stu(
/**char类型和varchar类型的区别:
*char的长度不可变,varchar长度可变,char插入的长度小于定长需要用空格填充,
*varchar不需要存多少是多少;
*/
	stu_id INT NOT NULL PRIMARY KEY auto_increment,
	stu_name CHAR(10) not null,
	stu_sex CHAR(2) not null,
	stu_age INT not NULL,
	stu_birth date NOT null,
	stu_address VARCHAR(200) not null
)

2. Delete the structure of the table

//删除创建的表tb_stu(DROP )
DROP TABLE tb_stu

3. Modify the fields in the table

//修改tb_stu表中的stu_name将其类型更改为VARCHAR类型(MODIFY )
ALTER TABLE tb_stu MODIFY stu_name VARCHAR(20) not null

4. Add a field to the table

//向表中添加一个字段:alter table 表名 add 字段名 类型 等
ALTER TABLE tb_stu ADD stu_email VARCHAR(40) 
ALTER TABLE tb_stu ADD stu_phone INT;

5. Delete a column of data in the table

//删除表中的一列数据:alter table 表名 drop 列名
ALTER TABLE tb_stu DROP stu_phone

Three, SQL statement

1. Add sentences

// 向tb_stu表的所有列插入一组数据
INSERT INTO tb_stu VALUES()//()中放表中的数据,默认数据用default
//如果一次插入多个数据,一个括号一组数据,每组数据之间用逗号隔开

2. Modify the sql statement

//格式:update tb_name set 字段名=字段值 where 条件(boolean)
//例:
//把学号为5的学生的姓名改为小强
UPDATE tb_stu set stu_name='小强' where stu_id=5
//		将学生姓名中带有“强”字的学生的年龄设置为30岁
UPDATE tb_stu set stu_age=30 where stu_name LIKE '%强%'

3. Delete the sql statement

删除sql语句格式:del:delete from tbl_name where 条件(boolean)

4. Query statement

一般查询:select  *   from  tb_stu
查询语句中  *  表示所有列
排序ORDER BY   升序ASC  降序DESC
分组   GROUP BY 
聚合函数:
COUNT:数量
SUM:和
AVG:平均数
MAX:最大值
MIN:最小值

LAST_INSERT_ID():最近一次添加的主键
HAVING  : 筛选
limit  参数1 ,参数2)参数1 为起始行,参数2 每次查询的条数:查询参数一到参数二的数据
DISTINCT :去除重复的数据

5. Multi-table connection operation

内连接:INNER JOIN
左外连接: LEFT JOIN(左外连接 左表全部显示,右表无则显示为null)
右外连接:RIGHT JOIN(右表全部显示,左表多的则不显示)

to sum up

This article mainly summarizes the recently learned SQL statements, just some simple SQL statements, SQL statements require strong logical thinking, and more need to be practiced by yourself. This article only represents personal understanding. If you have any questions, I hope you can correct me, thank you.

Guess you like

Origin blog.csdn.net/agoni101/article/details/115271183