MySQL——查询操做

简单查询

select 选择查询列表数据库

select [listname] from [tablename];
select [listname1] [listname2] from [tablename];

【 * 】 表示显示全部的列,和建立表时的顺序一致性能

避免重复数据

/* 去除列中重复的数据 */
select distinct [listname] from [tablename];
/* 去除每一个数据的列名一、列名2相同 */
select distinct [listname1] [listname2] from [tablename];

图片描述
图片描述

实现数学运算查询

整数、小数类型数据可使用(+ - * /)建立表达式
日期类型数据可以使用(+ -)建立表达式spa

/* 查询全部货品id,名称和批发价(卖价*折扣)*/
select id,productname,saleprice*cutoff from tablename;

/* 查询全部货品id,名称和买50个的成本价 */
select id,productname,costprice*50 from tablename;

设置列的别名

用于表示计算结果的含义
若是别名中使用特殊字符、强制大小写敏感、空格,都须要单引号设计

/* 给costprice*50取别名为XXX,其实as能够省略 */
select id,productname,costprice*50 as XXX from tablename;

设置显示格式查询

/* 格式:XXX商品零售价为:XXX */
select concat(productname,'商品零售价为:',saleprice) from tablename;

过滤查询

在from子句后面接where子句code

/* 表格中年龄为23的数据 */
select * from t_students where age = 23 ;

/* 表格中名字为杨敏豪的数据,字符串和日期要用单引号括起来 */
select * from t_students where name = '杨敏豪' ;

/* 列名的别名不能用于where子句 */
select name as mingzi from t_students where name != 'Mh' ;
  • 字符串和日期要用[ ' ]单引号括起来
  • 要MySQL查询时区分大小写:
/* 默认不区分大小写 */
select * from t_students where name = 'Mh' ;

/* 在where后面加binary区分大小写 */
select * from t_students where binary name = 'Mh' ;

图片描述

SQL的各个子句执行前后顺序:排序

  1. from:肯定使用哪一张表作查询
  2. where:从表中筛选出符合条件的数据
  3. select:将筛选的结果集中显示
  4. order by:排序
/* AND */
select * from product where saleprice>=300 AND saleprice<=400;
/* OR */
select * from product where saleprice=300 OR saleprice=400;
/* NOT */
select * from product where NOT saleprice=300 ;

若有多个查询条件,尽可能把过滤最多的条件放在最靠近where的地方,提升性能。图片

优先级 运算符
1 + - * /
2 NOT
3 AND
4 OR

范围查询

between-and,经常使用在数字类型/日期类型数据上,对于字符类型也可用。内存

/* 用between-and语句选择范围 */
select * from product where saleprice between 300 and 400;

select * from product where NOT saleprice  between 300 and 400;/*取反*/

集合查询

in,列的值是否存在于集合中,用于批量删除字符串

select * from product where id in (2,4);

空值查询

is null,判断列的值是否为空(NULL,不是指的空字符串)数学

select * from product where id is null;

图片描述

模糊查询

like,查询条件可包含文字或数字
【 % 】:能够表示零或任意多个字符
【 _ 】:可表示一个字符

/* 值以罗技M结尾的 */
select * from product where name like '%罗技M';

/* 值以罗技M开头的 */
select * from product where name like '罗技M%';

分页查询

  • 假分页/逻辑分页/内存分页:

一次性查询出全部的数据,存放在内存,每次翻页,都从内存中取出指定的条数。

特色:翻页较快,可是数据量过大时,可能形成内存溢出。
  • 真分页/物理分页/数据库分页(推荐):

每次翻页都从数据库截取指定的条数,假设每页10条数据,第一页:查询0~9条数据,第二页:查询10~19条数据。

特色:翻页比较慢,不会形成内存溢出

MySQL的分页设计:

int pagesize = n; /* 表示每页最多显示n条数据 */

分页查询结果集的SQL:

select * from tablename limit ?,?;

第一个[ ? ]:(当前页-1)*每页显示n条数据
第二个[ ? ]:每页显示n条数据

第一页:SELECT * FROM `test1`.`t_students` LIMIT 0,2
第二页:SELECT * FROM `test1`.`t_students` LIMIT 2,2
第三页:SELECT * FROM `test1`.`t_students` LIMIT 4,2
相关文章
相关标签/搜索