DQL
1 查询数据
【在navicat中完成】
右击新建查询
select * from students;
select sname,age from students;
select * from students
where sex='nan' and age =16;
在navicat中可以保存查询语句方便下次使用
select * from students
where sno=1 or sname='wc';
navicat中注释 ctrl+/
select * from students where sno in(1,2,3);
等同于 select * from students where sno=1 or sno=2 or sno=3;
select * from students where sname is null;
select * from students where sname is not null;
select * from students where sex!='nan';
select * from students where age>=5 and age<=12;
等同于select * from students where age between 5 and 12;
2 模糊查询
select * from students where sname like '_____';
-- 五个“_”
select * from students where sname like '____x';
select * from students where sname like 'm%';
select * from students where sname like '_s%';
select * from students where sname like '%s%';
3 字段控制查询
select distinct name from stu;
select *, age+score from students;
select *, ifnull(age,0)+ifnull(score,0) from students;
select *, ifnull(age,0)+ifnull(score,0) as total from students;
select sname as resname from students;
create table emp(
id int(11) not null,
name varchar(50) default null,
gender varchar(1) default null,
hire_date date default null,
salary decimal(10,0) default null,
performance double(255,0) default null,
manage double(255,0) default null,
department varchar(255) default null
);
-- decimal 定义时划定整数和小数的位数,decimal(10,0)指10位整数,0位小数
在“表”处右击刷新,看到我们新建的表
CREATE TABLE `emp` (
`id` int(11) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`gender` varchar(1) DEFAULT NULL,
`hire_date` date DEFAULT NULL,
`salary` decimal(10,0) DEFAULT NULL,
`performance` double(255,0) DEFAULT NULL,
`manage` double(255,0) DEFAULT NULL,
`department` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
4 排序
select * from employee order by salary;
等同于select * from employee order by salary ASC;
select * from employee order by salary DESC;
select * from employee order by salary DESC,id DESC;
5 聚合函数
select conut(*) from employee;
select count(*) from employee where salary>2500;
薪水加绩效大于5000的数据条数
select count(*) from employee
where ifnull(salary,0) + ifnull(performance,0)>5000;
select count(performance),count(manage) from employee;
select sum(salary) from employee;
select sum(salary),sum(performance) from emplyoee;
select sum(salary+ifnull(performance,0)) from emplyoee;
select avg(salary) from employee;
select max(salary) from employee;
select min(salary) from employee;