search
HomeDatabaseSQLOrganize and summarize basic SQL statements based on examples

This article brings you relevant knowledge about SQL, which mainly introduces the organization of basic SQL statements, including DDL, DML, DQL, etc. Let’s take a look at it together ,I hope everyone has to help.

Organize and summarize basic SQL statements based on examples

Recommended study: "SQL Tutorial"

1. DDL (Data Definition Language)

Data definition language, used to define database objects (databases, tables, fields)

Query

Query all databases

show databases;

Query the current database

select database();

Create

create database [if not exists] 数据库名 [default charset 字符集][collate 排序规则];

#中括号里的可加可不加,具体情况而定
#第一个是如果不存在相同名称的数据库则创建
#第二个是设置字符的字符集和排序规则

Delete

drop database [if exists] 数据库名;

#中括号是如果存在相同名称的数据库就删除

Using

use 数据库名;

Table Operation-Create

create table 表名 (
        字段1 字段1类型[comment 字段1注释],
        字段2 字段2类型[comment 字段2注释],
        字段3 字段3类型[comment 字段3注释],
        ......
        字段n 字段n类型[comment 字段n注释]
)[comment 表注释];

Note: [....] is an optional parameter, there is no comma after the last field

Table operation - modification

Add field

alter table 表名 add 字段名 类型(长度) [comment 注释][约束];

Modify data type

alter table 表名 modify 字段名 新数据类型(长度);

Modify field name and field type

alter table 表名 change 旧字段名 新字段名 类型(长度)[comment 注释][约束];

Delete field

alter table 表名 drop 字段名;

Modify table name

alter table 表名 rename to 新表名;

Table operation - delete

Delete table (make the specified table disappear from the database)

drop table [if exists] 表名;

Delete the specified table and re-create the table (commonly known as formatting)

truncate table 表名;

2. DML (Data Manipulation Language)

Data operation language, used to add, delete and modify data in database tables

auxiliary table creation format

create table worktable(
id int comment '编号',
worknum int comment '工号',
name varchar(20) comment '姓名',
sex char(1) comment '性别',
age int comment '年龄',
idcard int comment '身份证号',
entrydate date comment '入职日期'
)comment '员工信息表';

Add data

Add data to the specified field

insert into 表名(字段名1,字段名2,.....) values(值1,值2,......);

Add data to all fields

insert into 表名 values (值1,值2,.....);

Add data in batches

insert into 表名(字段名1,字段名2,.....) 
values(值1,值2,......),(值1,值2,......),(值1,值2,......);


insert into 表名 
values (值1,值2,.....),(值1,值2,......),(值1,值2,......);

[Note]:

· When inserting data, the specified field order needs to be in one-to-one correspondence with the value order

·String and date data should be enclosed in quotes

·The size of the inserted data, should Modify data within the specified range of the field

Modify data

update 表名 set 字段名1=值1,字段名2=值2,....[where 条件];

[Note]: The conditions for modifying the statement may or may not be , if there is no condition, all data in the entire table will be modified

Delete data

delete from 表名 [where 条件];

[Note]:

·The condition of the delete statement may or may not be present. If there is no condition, all data in the entire table will be deleted

·The delete statement cannot delete the value of a certain field (you can use update)

3. DQL (Data Query Language)

Data query language, used to query records in tables in the database

Overall syntax overview

select 字段列表
from 表名列表
where 条件列表
group by 分组字段列表
having 分组后条件列表
order by 排序字段列表
limit 分页参数
  • 基本查询
  • 条件查询(where
  • 聚合函数(count,max,min,avg,sum
  • 分组查询(group by
  • 排序查询(order by
  • 分页查询(limit

辅助建表内容

create  table emp(
id             int                comment '编号',
worknum        varchar(10)        comment '工号',
name           varchar(10)        comment '姓名',
gender         char(1)            comment '性别',
age            tinyint unsigned   comment '年龄',
idcard         char(18)           comment '身份证号',
workaddress    varchar(50)        comment '工作地址',
entrydate      date               comment '入职时间'
)comment '员工表';

insert into emp (id,worknum,name,gender,age,idcard,workaddress,entrydate)
values  (1,'1','柳岩','女',20,'123456789012345678','北京','2000-01-01'),
        (2,'2','张无忌','男',18,'123456789012345670','北京','2005-09-01'),
        (3,'3','韦一笑','男',38,'123456789712345670','上海','2005-08-01'),
        (4,'4','赵敏','女',18,'123456757123845670','北京','2009-12-01'),
        (5,'5','小昭','女',16,'123456769012345678','上海','2007-07-01'),
        (6,'6','杨逍','男',28,'12345678931234567X','北京','2006-01-01'),
        (7,'7','范瑶','男',40,'123456789212345670','北京','2005-05-01'),
        (8,'8','黛绮丝','女',38,'123456157123645670','天津','2015-05-01'),
        (9,'9','范凉凉','女',45,'123156789012345678','北京','2010-04-01'),
        (10,'10','陈友谅','男',53,'123456789012345670','上海','2011-01-01'),
        (11,'11','张士诚','男',55,'123567897123465670','江苏','2015-05-01'),
        (12,'12','常遇春','男',32,'123446757152345670','北京','2004-02-01'),
        (13,'13','张三丰','男',88,'123656789012345678','江苏','2020-11-01'),
        (14,'14','灭绝','女',65,'123456719012345670','西安','2019-05-01'),
        (15,'15','胡青牛','男',70,'12345674971234567X','西安','2018-04-01'),
        (16,'16','周芷若','女',18,null,'北京','2012-06-01');

基本查询

查询多个字段

select 字段1,字段2,字段3.....from 表名;
select *from 表名;

设置别名

select 字段1 [as 别名1],字段2 [as 别名2] .... from 表名;

#as可省略

去除重复记录

select distinct 字段列表 from 表名;

 

条件查询

语法

select 字段列表 from 表名 where 条件列表;

条件

比较运算符 功能 逻辑运算符 功能
> 大于 and 或 && 并且(多个条件同时成立)
>= 大于等于 or 或 || 或者(多个条件任意一个成立)
小于 not 或 ! 非,不是
小于等于

= 等于

或 != 不等于

between...and... 在某个范围内(含最小,最大值)

in(.....) 在in之后的列表中的值,多选一

like 占位符 模糊匹配(_匹配单个字符,%匹配任意个字符)

is null 是null

聚散函数

常见聚合函数

函数 功能
count 统计数量
max 最大值
min 最小值
avg 平均值
sum 求和

语法

select 聚合函数(字段列表) from 表名;

[注]:null值不参与所有聚合函数运算

分组查询

语法

select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组过滤条件];

where 与 having 区别

1.执行时机不同:where是分组之前进行过滤,不满足where条件,不参与分组;

                            having是分组之后对结果进行过滤。

2.判断条件不同:where不能对聚合函数进行判断,而having可以。

排序查询

语法

select 字段列表 from 表名 order by 字段1 排序方式1 , 字段2 排序方式2;

#排序方式
#asc:升序(默认值)
#desc:降序

[注]:如果是多字段排序,当第一个字段值相同时,才会根据第二个字段进行排序。

分页查询

语法

select 字段列表 from 表名 limit 起始索引,查询记录数;

[注]:

  • 起始索引从0开始,起始索引 = (查询页码 - 1) * 每页显示记录数
  • 分页查询是数据库的方言,不同的数据库有不同的实现,MySQL中是limit
  • 如果查询的是第一页数据,起始索引可以省略,直接简写为limit 10

案例练习

整体语法顺序


四、DCL(Data Control Language)

数据控制语言,用来创建数据库用户,控制数据库的访问权限

管理用户

查询用户

use mysql;
select *from user;

创建用户

create user '用户名'@'主机名' identified '密码';

 修改用户密码

alter user '用户名'@'主机名' identified with mysql_native_password by '新密码';

 删除用户

drop user '用户名'@'主机名';

 [注]:

  • 主机名可以使用%通配
  • 这类SQL开发人员操作的比较少,主要是DBA(Database Administrator)使用

权限控制

常用的权限

权限 说明
all,all privileges 所有权限
select 查询数据
insert 插入数据
update 修改数据
delete 删除数据
alter 修改表
drop 删除数据库/表/视图
create 创建数据库/表

查询权限

show grants for '用户名'@'主机名';

 授予权限

grant 权限列表 on 数据库名.表名 to '用户名'@'主机名';

撤销权限

revoke 权限列表 on 数据库名.表名 from '用户名'@'主机名';

 [注]:

  • 多个权限之间,使用逗号分割
  • 授权时,数据库名和表名可以使用 * 进行通配,代表所有

推荐学习:《SQL教程

The above is the detailed content of Organize and summarize basic SQL statements based on examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
What is Pattern Matching in SQL and How Does It Work?What is Pattern Matching in SQL and How Does It Work?May 13, 2025 pm 04:09 PM

PatternmatchinginSQLusestheLIKEoperatorandregularexpressionstosearchfortextpatterns.Itenablesflexibledataqueryingwithwildcardslike%and_,andregexforcomplexmatches.It'sversatilebutrequirescarefulusetoavoidperformanceissuesandoveruse.

Learning SQL: Understanding the Challenges and RewardsLearning SQL: Understanding the Challenges and RewardsMay 11, 2025 am 12:16 AM

Learning SQL requires mastering basic knowledge, core queries, complex JOIN operations and performance optimization. 1. Understand basic concepts such as tables, rows, and columns and different SQL dialects. 2. Proficient in using SELECT statements for querying. 3. Master the JOIN operation to obtain data from multiple tables. 4. Optimize query performance, avoid common errors, and use index and EXPLAIN commands.

SQL: Unveiling Its Purpose and FunctionalitySQL: Unveiling Its Purpose and FunctionalityMay 10, 2025 am 12:20 AM

The core concepts of SQL include CRUD operations, query optimization and performance improvement. 1) SQL is used to manage and operate relational databases and supports CRUD operations. 2) Query optimization involves the parsing, optimization and execution stages. 3) Performance improvement can be achieved through the use of indexes, avoiding SELECT*, selecting the appropriate JOIN type and pagination query.

SQL Security Best Practices: Protecting Your Database from VulnerabilitiesSQL Security Best Practices: Protecting Your Database from VulnerabilitiesMay 09, 2025 am 12:23 AM

Best practices to prevent SQL injection include: 1) using parameterized queries, 2) input validation, 3) minimum permission principle, and 4) using ORM framework. Through these methods, the database can be effectively protected from SQL injection and other security threats.

MySQL: A Practical Application of SQLMySQL: A Practical Application of SQLMay 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

Comparing SQL and MySQL: Syntax and FeaturesComparing SQL and MySQL: Syntax and FeaturesMay 07, 2025 am 12:11 AM

The difference and connection between SQL and MySQL are as follows: 1.SQL is a standard language used to manage relational databases, and MySQL is a database management system based on SQL. 2.SQL provides basic CRUD operations, and MySQL adds stored procedures, triggers and other functions on this basis. 3. SQL syntax standardization, MySQL has been improved in some places, such as LIMIT used to limit the number of returned rows. 4. In the usage example, the query syntax of SQL and MySQL is slightly different, and the JOIN and GROUPBY of MySQL are more intuitive. 5. Common errors include syntax errors and performance issues. MySQL's EXPLAIN command can be used for debugging and optimizing queries.

SQL: A Guide for Beginners - Is It Easy to Learn?SQL: A Guide for Beginners - Is It Easy to Learn?May 06, 2025 am 12:06 AM

SQLiseasytolearnforbeginnersduetoitsstraightforwardsyntaxandbasicoperations,butmasteringitinvolvescomplexconcepts.1)StartwithsimplequerieslikeSELECT,INSERT,UPDATE,DELETE.2)PracticeregularlyusingplatformslikeLeetCodeorSQLFiddle.3)Understanddatabasedes

SQL's Versatility: From Simple Queries to Complex OperationsSQL's Versatility: From Simple Queries to Complex OperationsMay 05, 2025 am 12:03 AM

The diversity and power of SQL make it a powerful tool for data processing. 1. The basic usage of SQL includes data query, insertion, update and deletion. 2. Advanced usage covers multi-table joins, subqueries, and window functions. 3. Common errors include syntax, logic and performance issues, which can be debugged by gradually simplifying queries and using EXPLAIN commands. 4. Performance optimization tips include using indexes, avoiding SELECT* and optimizing JOIN operations.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool