查询
关系运算符
<,>,!=(<>),=
逻辑运算符
and,or,not
in between
in查询的是指定的内容in(20,40)
between查询的是一个范围between 20 and 40(相当于>=and<=)
条件查询
查询一个年龄大于18的女孩或者等于16岁的
SELECT * FROM user WHERE (age > 18 AND sex = "女") or age = 16;
查询年龄不为40
SELECT * FROM user where age <> 40;
查询年龄小于18或为女性
SELECT * FROM user WHERE age < 18 or sex = "女";
查询有性别的
SELECT * FROM user WHERE sex is NOT null;
所有的人的年龄和、年龄最大的谁?最小的?平均年龄是多少?聚合函数 sum max min avg 平均值 列的别名 as(可以省略)
SELECT SUM(age) as 年龄和,MAX(age) 最大年龄,MIN(age) AS 最小年龄,avg(age) AS 平均 from user;
部门共有多少人?
SELE9CT COUNT(id) FROM user;
模糊查询
SELECT * FROM user WHERE username LIKE
'%刘%'
%表示通配 查询含有刘的
SELECT * FROM user WHERE username LIKE '刘%'
查询以刘开头的
SELECT * FROM user WHERE username LIKE '_刘%'
查询第二个字是刘的 _表示占位
排序
order by 列名 [asc|desc]
默认为asc,为正序排列
desc为倒叙排列
分组查询
group by
SELECT sex, COUNT(*) from user where true and GROUP BY sex having sex is not NULL
having 筛选 # 对于分组的数据进行二次过滤 写在group by 后,有having必有group by 有group by不一定有having
分页查询
limit
SELECT * from user LIMIT x,y
从x开始查询y条
当前页 pageNow
每页显示多少条 pageSize
总共的条数 allCount select count(*) from user
总共有多少页? pageAll = allCount % pageSize == 0 ? pageAll = allCount % pageSize : pageAll = allCount % pageSize + 1
SELECT * from user where LIMIT (pageNow-1)*pageSize ,pageSize
将两个表外链到一起
create TABLE dept(
id int PRIMARY KEY auto_increment,
name VARCHAR(50),
description VARCHAR(255)
)
create TABLE emp(
id int PRIMARY KEY auto_increment,
name VARCHAR(20) NOT NULL,
age INT,
sex VARCHAR(6),
tel VARCHAR(20),
address VARCHAR(255),
deptId int,
CONSTRAINT FOREIGN key(deptId) REFERENCES dept(id)
)
张三的部门名称
SELECT name from dept where id = (SELECT deptId from emp where name = '张三')
SELECT dept.name
FROM emp,dept
WHERE emp.name = "张三" AND emp.deptId = dept.id