1.基本查询语句
select 属性列表 from 表名和视图列表 [where 条件表达式1] [group by 属性名1 [having 条件表达式2]] [order by 属性名2 [asc|desc]]
2.单表查询
1)使用*查询所有字段
select * from 表名;
2) 查询指定字段
select id,name from product;
使用上面例子可以查询指定字段
3)查询指定记录
where 条件表达式
实例:
select *from employee where id = 1002;
where 子句常用查询条件
比较:=、<、 <=、 >、 >=、 !=、 <>、 !>、 !<
指定范围 : between and、not between and
指定集合:in、not in
匹配字符: like、not like
是否为空值:is null 、is not null
多条件查询:and or
4)带in关键字的查询
in关键字可以判断某个字段的值是否在指定的集合中。
[not] in (元素1,元素2,...,元素n)
实例:
select * from employee where id in (1001,1002);
如果集合中的元素为字符时,需加上单引号。
5)带between and 的范围查询
[not] between 取值1 and 取值2
取值1为起始值,取值2为终止值
实例:
select * from employee where age bewteen 15 and 20;
6)带like的字符串匹配查询
[not] like ‘字符串’;
‘字符串’的值可以是完整的字符串,也可以是含百分号(%)或下滑线(_)的通配字符。
“% ”可以代表任意长度的字符串,长度可以是0。
“_”只能表示单个字符。
完整字符时like相当于“=”。
实例:
select * from employee where homeaddr like ‘北京%’;
查询所有homeaddr字段中以“北京”
开头的记录。
select * from employee where name like "ar_c";
查询所有name字段值长度为4,前两个字母为“ar”最后一个字母为“c”的记录。
统配的字符串可以用单引号或双引号。
通配符“_”可以多次使用,如“赵 _ _”。
7)查询空置
is [not] null
实例:
select * from work where info is null;
查询work表info字段为空的记录。
8)and 和 or多条件查询
条件表达式1 and 条件表达式2 [...and 条件表达式n]
and 表示同时满足所有条件的记录会被查询出来,or表示只要满足其中一条的记录就会被查询出来。
9)查询结果不重复
select distinct 属性名
实例:
select distinct age department_id employee;
10) 查询结果排序
order by 属性名 [asc|desc]
默认asc排序。
如果遇到某个字段存在空值的记录,需要注意,空值排序时可以理解为该字段的最小值。
mysql中可以指定按多字段排序。
实例:
select * from employee order by id asc , age desc;