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
The Importance of SQL: Data Management in the Digital AgeThe Importance of SQL: Data Management in the Digital AgeApr 23, 2025 am 12:01 AM

SQL's role in data management is to efficiently process and analyze data through query, insert, update and delete operations. 1.SQL is a declarative language that allows users to talk to databases in a structured way. 2. Usage examples include basic SELECT queries and advanced JOIN operations. 3. Common errors such as forgetting the WHERE clause or misusing JOIN, you can debug through the EXPLAIN command. 4. Performance optimization involves the use of indexes and following best practices such as code readability and maintainability.

Getting Started with SQL: Essential Concepts and SkillsGetting Started with SQL: Essential Concepts and SkillsApr 22, 2025 am 12:01 AM

SQL is a language used to manage and operate relational databases. 1. Create a table: Use CREATETABLE statements, such as CREATETABLEusers(idINTPRIMARYKEY, nameVARCHAR(100), emailVARCHAR(100)); 2. Insert, update, and delete data: Use INSERTINTO, UPDATE, DELETE statements, such as INSERTINTOusers(id, name, email)VALUES(1,'JohnDoe','john@example.com'); 3. Query data: Use SELECT statements, such as SELEC

SQL: The Language, MySQL: The Database Management SystemSQL: The Language, MySQL: The Database Management SystemApr 21, 2025 am 12:05 AM

The relationship between SQL and MySQL is: SQL is a language used to manage and operate databases, while MySQL is a database management system that supports SQL. 1.SQL allows CRUD operations and advanced queries of data. 2.MySQL provides indexing, transactions and locking mechanisms to improve performance and security. 3. Optimizing MySQL performance requires attention to query optimization, database design and monitoring and maintenance.

What SQL Does: Managing and Manipulating DataWhat SQL Does: Managing and Manipulating DataApr 20, 2025 am 12:02 AM

SQL is used for database management and data operations, and its core functions include CRUD operations, complex queries and optimization strategies. 1) CRUD operation: Use INSERTINTO to create data, SELECT reads data, UPDATE updates data, and DELETE deletes data. 2) Complex query: Process complex data through GROUPBY and HAVING clauses. 3) Optimization strategy: Use indexes, avoid full table scanning, optimize JOIN operations and paging queries to improve performance.

SQL: A Beginner-Friendly Approach to Data Management?SQL: A Beginner-Friendly Approach to Data Management?Apr 19, 2025 am 12:12 AM

SQL is suitable for beginners because it is simple in syntax, powerful in function, and widely used in database systems. 1.SQL is used to manage relational databases and organize data through tables. 2. Basic operations include creating, inserting, querying, updating and deleting data. 3. Advanced usage such as JOIN, subquery and window functions enhance data analysis capabilities. 4. Common errors include syntax, logic and performance issues, which can be solved through inspection and optimization. 5. Performance optimization suggestions include using indexes, avoiding SELECT*, using EXPLAIN to analyze queries, normalizing databases, and improving code readability.

SQL in Action: Real-World Examples and Use CasesSQL in Action: Real-World Examples and Use CasesApr 18, 2025 am 12:13 AM

In practical applications, SQL is mainly used for data query and analysis, data integration and reporting, data cleaning and preprocessing, advanced usage and optimization, as well as handling complex queries and avoiding common errors. 1) Data query and analysis can be used to find the most sales product; 2) Data integration and reporting generate customer purchase reports through JOIN operations; 3) Data cleaning and preprocessing can delete abnormal age records; 4) Advanced usage and optimization include using window functions and creating indexes; 5) CTE and JOIN can be used to handle complex queries to avoid common errors such as SQL injection.

SQL and MySQL: Understanding the Core DifferencesSQL and MySQL: Understanding the Core DifferencesApr 17, 2025 am 12:03 AM

SQL is a standard language for managing relational databases, while MySQL is a specific database management system. SQL provides a unified syntax and is suitable for a variety of databases; MySQL is lightweight and open source, with stable performance but has bottlenecks in big data processing.

SQL: The Learning Curve for BeginnersSQL: The Learning Curve for BeginnersApr 16, 2025 am 12:11 AM

The SQL learning curve is steep, but it can be mastered through practice and understanding the core concepts. 1. Basic operations include SELECT, INSERT, UPDATE, DELETE. 2. Query execution is divided into three steps: analysis, optimization and execution. 3. Basic usage is such as querying employee information, and advanced usage is such as using JOIN connection table. 4. Common errors include not using alias and SQL injection, and parameterized query is required to prevent it. 5. Performance optimization is achieved by selecting necessary columns and maintaining code readability.

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 Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.