SQL语言学习(1)

DDL 数据定义语言(管理数据结构的)

  1. 创建数据库:

    create database 数据库名 charset utf8;

  2. 显示所有数据库:

    show databases;

  3. 使用数据库

    use 数据库

  4. 创建表:表:存储数据的单位

    用户表:用户Id、用户名、用户年龄

    create table user (id int, age int, username varchar(10));

  5. 显示所有的表:

    show tables;

  6. 查表的字段:

    desc 表名;

  7. 给表加字段:

    alter table 表名 add 字段名 字段类型;

  8. 修改字段的类型

    alter table 表名 modify 字段名 字段类型;

  9. 删除字段

    alter table 表名 drop 字段名;

  10. 修改表名

    rename table 原名字 to 新名字;

  11. 查看建表细节

    show create table 表名;

  12. 修改表的字符集

    alter table 表名 character set 字符集名称;

  13. 修改列名

    alter table 表名 change 原始列名 新列名 字段类型;

  14. 删除表

    drop table 表名;

DML 管理数据

  1. 查询所有的数据

    select * from 表名 \G;

  2. 插入数据

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

  3. 更新数据

    update 表名 set 列名=列值 where 列名=列值;

  4. 删除记录

    delete from 表名 where 列名=值; 删除数据可以找回

    truncate table 表名; 删除整个表,在重现建立一个一样结构的表,数据不能找回

DQL 数据查询语句

  1. 查询所有数据

    select * from 表名;

  2. 查询制定数据

    select 指定字段 from 表名;

  3. 条件查询

    select * from 表名 where 条件; 条件可以用到:= != <> <= < >= >、between...and...

  4. 查询年龄17~15

    select * from stu where age between 15 and 17;

  5. 查询年龄在17 并且sid=5的

    select * from stu where age=17 and sid=5;

    查询年龄15或id=1

    select * from stu where age=15 or id=1;

    and or is null is not null

  6. 模糊查询 like

    _代表一个字符 %代表多个字符

    查询name 姓马的

    select * from stu where name like 马%;

  7. 排序 order by

    升序 ase

    select * from stu order by age ase; //按年龄升序

    降序 desc

    select * from stu order by age desc; //按钮年龄降序

  8. 聚合函数

    count(字段名) 统计不为null的行数

    max(字段名) 最大值

    min(字段名) 最小值

    sum(字段名) 求和

    avg(字段名) 计算平均自

  9. 分组 group by 字段名

    select * from stu group by age; 按年龄分组显示

  10. 关键字顺序

    书写顺序 select(5) from(1) where(2) group by(3) having(4) order by(6) limit(7)

    分页 limit int (下标,表示从那个开始), int (表示显示几个)

  11. 约束

    primary key 主键约束 唯一而不为空

    unique 唯一

    auto_increment 自增

    not null 不为空

    例如:create table teacher(id int primary key auto_increment, name varchar(10));

  12. 多表联查 查出每个学生对应的老师的名字

    99查询

    select student.name, teacher.tname from student,teacher where student.id=teacher.sid;

    内连接 join on

    select * from 表一 join 表二 on 条件;

    select * from student join teacher on student.id=teacher.sid;

    左外连接和右外连接

    select * from student left join teacher on student.id=teacher.sid; 左外连接把左表剩下的数据拿出

  13. 索引 加快查询效率

    创建索引

    create index 索引名 on 表名 (字段)

    删除索引

    drop index 索引的名称 on 表名

    查看索引

    show index from 表名

posted @ 2019-05-21 16:47  Hello-Tiger  阅读(182)  评论(0)    收藏  举报