常用MySQL语句

1、库操作

  新增  create database

  查看  show databases

  删除  drop database

  选择  use 

2、表操作

  (1)新增一张表

create table 表名(
字段1 字段类型 约束,
字段2 列类型 约束
);

  字段类型有以下:

    整数:tinyint、smallint、mediumint、int、bigint

    小数:float、double、decimal

    字符:char、varchar

    日期:year、date、time、datetime

  常用约束:primary key(主键,主键唯一且不为空)、not null、default、unique

  (2)查看表结构 :desc 表名

  (3)查看 所有表:show tables

  (4)删除表: drop table 表名

  (5)表中某一字段的操作

      新增:alter table 表名 add 字段 字段类型 约束 frist/after 列名;

      删除:alter table 表名 drop 列名;

3、数据操作

  (1)新增

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

  (2)删除

   delete from 表名;  可以使用where,只删除某一条数据

     truncate,删除整个表

  (3)修改

   update 表名 set  字段=值;

  (4)查询

select 字段 fromwhere 条件 group by 列名 having 条件(从分组的结果提取)order by 字段 limit m,n 

  where 常用条件:

    比较(<,>,=)、and、or、not、between...and、in、not in、is null、is not null

    模糊查询 like,和通配符一起使用,常用的有:%  任意字符, _  一个字符

  group by 分组语句,常用分组条件:

    max(字段)、min、sum、avg、count

    注意:分组后查询的数据只能是 max / min / sun / avg / count,或者是分组的字段,查询其他数据无意义,数据不准确。

  having   从分组的结果上进行二次筛选

  order by 对查询结果进行排序,常用的有 : order by 字段 desc ,order by 字段 asc 

    limit m,n  意思是跳过m个记录向后取n条数据,m不写默认为0,可用 limit 1 取一条数据,

  查询结果去重关键字 distinct:

    select distinct 字段1,字段2 

    select count(distinct 字段1) 先去重,再计数

  多表查询(其中  tableA.字段 和 tableB.字段 相同)

  1.使用where 条件

select * from tableA,tableB where tableA.字段=tableB.字段; 

  2.左连接,以左边表为基础,左边的表符合过滤条件的都筛选出来,右边的表若能匹配的记录,直接匹配,否则补NULL。

select * from tableA left join tableB on tableA.字段=tableB.字段 Where ...

  3.右连接:以右边表为基础,右边的表符合过滤条件的都筛选出来,左边的表若能匹配的记录,直接匹配,否则补NULL。

select * from tableA right join tableB on tableA.字段=tableB.字段 Where ...
原文地址:https://www.cnblogs.com/yjh1995/p/12121926.html