Mysql基础(三)—— 单表查询

1.插入单条数据:

insert into 表名(field1, field2,...fieldn) values (value1,value2,...valuen);

2.插入多条数据:

insert into 表名(field1, field2,...fieldn) values (value1,value2,...valuen),

                        (value1,value2,...valuen),

                          ......

                        (value1,value2,...valuen);

注意点:列跟值要一一对应;

    有默认值的列可以不用写出来;

    若插入失效,可能定义时出现问题,比如修改:alter table 表名 modify 列名 varchar(10);

3.更新数据:

特定数据:update 表名 set filed1=value1, field2=value2 where condition

所有数据:update 表名 set field2=value2;

4.删除数据:

特定数据:delete from table_name where condition;

所有数据:delete from table_name;

5.查询数据-单表:

select * from table_name;

去重:distinct

select distinct job from 表名;

可四则运算:+ - * / 

select 列1,列2*12 from 表名;

别名:as,as也可省略

select name as "姓名",sale*12 as "年薪" from 表名;

格式化显示:concat()连接字符串

select concat(name, "的年薪为:", sal*12) "薪资" from 表名;

where语句中,条件记录查询:

  支持比较运算符:> ,<, =, !=(<>),>=,<=.

  支持逻辑运算符:AND(&&)逻辑与,OR(||)逻辑或,XOR逻辑异或,NOT(!)逻辑非

  is null,is not null .----为空和空字符串不是一回事,Null指没有设置值,空字符串指值为空字符串。

    错误写法:!=null

  in关键字,not in.

    ...where name in ("a","b","c");

    ...where name not in ("a","b","c");

  like 关键字:支持通配符 “_”,"%",

    如:...where name like "A%";

      ...where name like "%A%";

      ...where name not like "_A%";

      ...where not name  like "_A%";

  排序order:

    order by 列名 asc;默认升序。

    order by 列名1 asc,列名2 desc;

  限制记录查询:limit 起始,行数;

    ...limit 2;   前两条数据

    ...limit 2,2;  从第2条开始的2行数据

  between  and:  

    ...where c between a and b; 相当于: ...where c>=a and c<=b;

    ...where c not between a and b;相当于:...where c<a and c>b;

6.统计函数--聚合函数

常见统计函数:count(),avg(),sum(),max(),min()

count(*): 统计所有的记录,不管是null值还是非null值

以下统计非null值:

  count(某列): 对指定字段进行统计,

  avg(某列):非null值得平均值

  sum(某列):非null的求和

  max(某列):非null最大值

  min(某列):非null最小值

如果没有记录,count返回0,其他函数返回null。

7. group by :分组记录查询,常与统计函数一起使用。

      也可以是多个字段分组:...group by 列1,列2;

8. having子句:筛选分组后的各种数据。

重点:写顺序: select...from...where...group by...having...order by...limit ;

       where 先筛选 分组后having再筛选

where和having的区别

  区别一:where 关键字无法与聚合函数一起使用。having 子句可以让我们筛选分组后的各组数据;

  区别二:where 数据从磁盘读入内存字段,不能用select中的别名,不能用统计函数,而having数据来自select中的字段和别名选择,再加上可用统计函数。

  区别三:顺序不一样;

  区别四:having语句不能单独出现,前面必须要有group by.

重点:最后执行顺序:from>where>group by > having > select>order by >limit

原文地址:https://www.cnblogs.com/lverkou/p/12957214.html