mysql数据库基础

mysql是一种关系型数据库

数据库的操作:

  进入mysql服务器:

    mysql -u 自己的用户名 -p  回车后输入密码

  查看数据库:

    show databases;

  创建数据库:

    create database 数据库名 charset utf8;

  删除数据库:(慎用,删库真的很危险)

    drop database 数据库名;

  使用数据库:

    use 数据库名;

表的操作:(表操作前需先进入数据库)

  创建表:

    create table 表名(字段 数据类型 [约束条件], 字段 数据类型 [约束条件]);

  删除表结构:

    drop table 表名;

  修改表:

    改表名: alter table 原表名 rename to 新表名;

    添加列: alter table 表名 add 字段名 数据类型 [约束];

    删除列:alter table 表名 drop 字段名;

  查看表结构:

    desc 表名;

数据的操作:

  添加数据:

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

  删除数据:

    delete from 表名 [where 条件];

  更新数据:

    update 表名 set 列名=值, …… where 条件;

  查询数据:

    基本查询:

      select * from 表名 [where 条件]; -->(依条件)查找所有

      select name as 姓名, gender 性别 from student;  -->只显示指定列并起别名,as可省略

      select distinct 列名 from 表名;  --> 列名前使用distinct可消除重复行

    模糊查询:

      select * from 表名 where name like '%x%'; -->从表中查找name中包含x的数据

      其中‘%’表示通配符,代表任意多个字符,也可以使用‘_’,表示一个任意字符

    范围查找:

      select  * from student where age in(18, 21); -->查找学生表中年龄是18和21的

      select * from student where age between 19 and 21; --> 查找年龄在[19,21]之间的学生(包含19和21)

      in() : 通常用做不连续的区间,或数据较少时

      between……and……:连续区间时使用,表示在……到……之间

    排序:

      select * from 表名 [where 条件] order by 列名 [asc|desc]; --> 按指定列将数据排序,默认升序

      当有条件语句时,将order by 语句放条件语句后。

      asc升序,可不写,默认为升序排序;降序排序时,列明后加desc

    分组:

      select 列名, count(*) from 表名 [where 查询条件] group by 字段 [having 条件];

      having 后加分组的条件,是分组的依据,没有课不写;

      两个条件的执行顺序是先过滤,后分组

    分页:

      select 字段 from 表名 [where 条件] [order by 字段 [asc|desc]] limit start, lenght;

      start :本页数据起始值。

      lenght :本页数据数量。

      列: 1页10条数据;第一页start是1,lenght是10;第二页start是11,lenght10;依次类推

   连接查询:

    内连接:

      select 字段 from 表1 inner join 表2 on 连接条件;

      查找结果为 连接条件 成立的存在于两张表中的数据

    左外链接:

      select 字段 from 表1 left join 表2 on 连接条件;

      表1位主表,表2为附表,主表结果不会丢失,没有的字段会以NULL显示

    右外连接:

      select 字段 from 表1 right join 表2 on 连接条件;

      表2位主表,表1为附表,主表结果不会丢失,没有的字段会以NULL显示

    

  

  

原文地址:https://www.cnblogs.com/fansirs/p/13472510.html