MySQL的 DDL和DML和DQL的基本语法
发布日期:2025-04-18 06:02:48 浏览次数:35 分类:精选文章

本文共 1706 字,大约阅读时间需要 5 分钟。

了解SQL语法的注意事项

SQL语句可以单行或多行书写,通常以分号结尾。为了提高可读性,可以使用空格和缩进。MySQL数据库的SQL语句不区分大小写,关键字建议使用大写。SQL提供了三种注释方式:

  • 单行注释:-- 注释内容# 注释内容(MySQL特有)
  • 多行注释:/* 注释 */

  • 一、DDL(数据定义语言)

    DDL用于定义和管理数据库对象,如数据库、表等。常用的命令包括CREATEDROPALTER。以下是操作数据库和表的示例:

    -- 查看所有数据库show databases;-- 创建新数据库create database ku;-- 删除数据库drop database ku;-- 使用特定数据库use ku;-- 查看库中表show tables;-- 创建新表create table tab_teacher (    tea_name varchar(10),    tea_sex char(1),    tea_birthday datetime,    tea_money decimal(20,1));-- 查看表结构show create table tab_teacher;

    二、DML(数据操作语言)

    DML用于操作数据库中的数据,常用的命令包括INSERTDELETEUPDATE。以下是操作数据的示例:

    -- 插入数据insert into student (sid, sname, birthday, ssex, classid) values (9, '张三', '1999-1-1', '男', 3);-- 插入多条数据insert into student (sname, ssex) values ('王帅帅', '男'), ('王靓靓', '男'), ('王妹妹', '女');-- 插入数据时忽略主键自增insert into student (sname) values ('老王');-- 插入新表时数据create table newstu select sname, birthday, ssex from student;-- 更新数据update stu1 set xingming = '赵雷雷' where sid = 1;-- 删除数据delete from student where sname = '老王';

    三、DQL(数据查询语言)

    DQL用于查询数据库中的数据,主要命令是SELECT。以下是查询数据的示例:

    -- 查询所有数据select * from student;-- 查询指定字段select sid, sname, birthday, ssex, classid from student;-- 查询结果的别名select sname as '姓名', birthday as '生日', ssex as '性别' from student;-- 去重查询select distinct ssex, classid, sid from student;-- 条件查询select * from student where ssex = '男' and birthday < '1990-1-1';-- 模糊查询select * from student where sname like '%张%';-- 范围查询select * from student where sid between 10 and 15;

    四、聚合函数

    聚合函数用于对一列数据进行统计和分析。常见的聚合函数包括COUNTAVGSUMMAXMIN等。以下是使用聚合函数的示例:

    -- 统计总人数select count(*) from student;-- 计算平均分select avg(score) from sc;-- 查询总成绩和平均分select count(*), sum(score), avg(score) from sc;

    结语

    以上仅为SQL语法的基础介绍,实际应用中可以结合具体需求进一步学习和实践。

    上一篇:mysql的 if else , case when then, IFNULL
    下一篇:Mysql百万级数据查询优化

    发表评论

    最新留言

    路过,博主的博客真漂亮。。
    [***.116.15.85]2026年06月16日 04时05分21秒