MySQL操作语句

数据定义语句(DDL):

数据库的操作:

  1. 数据库的创建
    create table 数据库名称;
  2. 查看数据库
    show database;
    show create database 数据库名称;
  3. 修改数据库
    alter database 数据库名称 default character set 编码方式 collate 编码方式_bin;
  4. 删除数据库
    drop database 数据库名称;
  5. 使用数据库
    use 数据库名称;

数据库表的操作:

  1. 表的创建
Create table 表名(
列名 类型[长度] 约束1 约束2 ……,
列名 类型[长度] 约束1 约束2 ……,
…
列名 类型[长度] 约束1 约束2 ……,
[表级约束]
); 

在这里插入图片描述

  1. 表的修改
    语法:
    Alter table 表名 add | drop | modify | change column 列名 [列类型 约束];
    ①修改列名
    Alter table user change column name username varchar(20);
    ②修改列的类型和约束
    Alter table user modify column username varchar(20) unique;
    ③修改添加新列
    Alter table user add column date datetime;
    注意:添加新列到指定位置
    first 和 after,first 表示添加列到表的第一列,after 表示添加在某个列之后。
    语法:alter table book add column 字段名 类型 约束 [first | after 列名]
    默认添加到最后一列。
    ④删除列
    Alter table user drop column date;
    ⑤修改表名
    Alter table user rename to user2;

  2. 表的删除
    Drop table if exists user;

  3. 查看表
    查看所有的表:Show tables;
    查看某一个表:Desc table user;

  4. 表的复制
    表1是已存在的表,表2不存在的表
    ①只复制表的结构
    Create table 表2 like 表1;
    ②复制数据+内容
    Create table 表2 like select * from 表1;
    ③复制部分数据
    Create table 表2 like select * from 表1 where 条件;
    ④仅仅复制某些字段
    Create table 表2 like select 字段1 ,字段2 from 表1 where 0;

数据操作语言(DML):

  1. 插入数据:insert
    insert into table_name values (value1, value2,...valueN); //向表中所有列插入数据
    Insert into table_name ( 列名1, 列名2,...列名N ) values ( value1, value2,...valueN );//向表中某些列插入数据
  2. 删除数据:delete
    delete from table_name [where clause];
  3. 修改数据:update
    update table_name set field1=new_value1, field2=new-value2[where clause];
  4. 查询数据:select
    select * from table_name [where clause];

数据查询语言(DQL):

查询指定列的数据:
select col1,col2,col3,... from table_name [where clause];
定义别名:
select col1 name1,col2 name2,col3 name3,... from table_name [where clause];
select col1 as name1,col2 as name2,col3 as name3,... from table_name [where clause];
消除重复:
select distinct col1 from table_name [where clause];
限定结果集的行数:
select top5 col1,col2,col3,... from table_name [where clause];//结果集的前5行
select top10 percent col1,col2,col3,... from table_name [where clause];//结果集的前10%行
计算列的值:
select score1,score2,score1+score2 as score from table_name [where clause];//计算并显示总成绩
聚合函数:

函数 功能
avg(<字段表达式>) 求一列数据的平均值
sum(<字段表达式>) 求一列数据的和
min(<字段表达式>) 求列中数据的最小值
max(<字段表达式>) 求列中数据的最大值
count(* 字段名)

猜你喜欢

转载自blog.csdn.net/Lzy410992/article/details/106232501