简单查询
select 选择查询列表
select [listname] from [tablename];
select [listname1] [listname2] from [tablename];
【 * 】 表示显示所有的列,和创建表时的顺序一致
避免重复数据
/* 去除列中重复的数据 */
select distinct [listname] from [tablename];
/* 去除每个数据的列名1、列名2相同 */
select distinct [listname1] [listname2] from [tablename];
实现数学运算查询
对整数、小数类型数据可以使用(+ - * /)创建表达式
对日期类型数据可使用(+ -)创建表达式
/* 查询所有货品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子句
/* 表格中年龄为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的各个子句执行先后顺序:
- from:确定使用哪一张表做查询
- where:从表中筛选出符合条件的数据
- select:将筛选的结果集中显示
- 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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。