Mysql简单查询操作

1、初始化三张表:

部门表:

CREATE TABLE dept(
	DEPTNO int(10) primary key auto_increment COMMENT '部门编号', 
	DNAME VARCHAR(20) not null COMMENT '部门名称', 
	LOC VARCHAR(20) not null COMMENT '部门位置'
	
);

INSERT INTO dept VALUES(10,'技术部','安徽');
INSERT INTO dept VALUES(20,'财务部','上海');
INSERT INTO dept VALUES(30,'测试部','北京');

员工表:

create TABLE emp(
	EMPNO int primary key COMMENT '员工编号',
	ENAME VARCHAR(10) not null COMMENT '员工姓名',
	JOB VARCHAR(20) not null COMMENT '职位',
	MGR int  COMMENT '员工领导编号',
	HIREDATE date DEFAULT NULL COMMENT '入职时间',
	SAL int COMMENT '基本工资',
	COMM int COMMENT '奖金',
	DEPTNO int COMMENT '所属部门编号',
	CONSTRAINT dept_id_fk FOREIGN KEY (DEPTNO) REFERENCES dept(DEPTNO) -- 添加外键
);

INSERT INTO emp VALUES(001,'wlj','技术经理',00001,null,6000,1000,10);
INSERT INTO emp VALUES(002,'xhq','业务经理',00002,null,5500,1000,10);
INSERT INTO emp VALUES(003,'dmh','文艺总监',00003,null,5000,1000,10);
INSERT INTO emp VALUES(004,'snm','销售总监',00004,null,3000,1000,10);
INSERT INTO emp VALUES(005,'tom','员工',00005,null,3000,300,10);
INSERT INTO emp VALUES(006,'jack','员工',00006,null,3000,300,10);
INSERT INTO emp VALUES(007,'zs','员工',00007,null,3000,300,10);
INSERT INTO emp VALUES(008,'ls','员工',00008,null,3000,300,10);

 工资等级表:

CREATE TABLE salgrade(
	id int COMMENT '工资等级编号',
	LOSAL int COMMENT '该等级的最低工资',
	HISAl int COMMENT '该等级的最该工资'
);

INSERT into salgrade VALUES(1,500,1000);
INSERT into salgrade VALUES(1,1000,2000);
INSERT into salgrade VALUES(1,2000,9999);

 2、mysql简单查询:

2.1、查询emp所有数据:

* 代表所有列

select * from 表名

2.2投影:

就是显示表中的部分字段

select 字段名,字段名 from 表名 

2.3别名:

select 别名.字段名  from 表名 别名

2.4去除重复数据:

关键字:distinct

select  distinct 别名.字段名 from 表名 字段名; 

2.5连接显示(关键字:CONCAT):

要求最后的结果展示 效果如下:

员工编号:001,员工姓名:wlj

把多列合并成一个列进行显示:

SELECT CONCAT("员工编号:",别名.字段名,",员工姓名:",别名.字段名) as "员工信息" from 表名 别名;

2.6限定查询(条件查询 关键字:where、in、or、and):

限定查询就是按照条件查询,只选出对自己有用的数据,关键字:where,where后面可以跟多个筛选条件

2.6.1统计基本工资高于2000的员工

SELECT * from 员工表 where 基本工资字段 > 2000;

2.6.2查询员工基本工资在3000到5000包含3000、5000的员工:

select * from 表名 别名 where 别名.字段名 >=3000 and 别名.字段名 <= 5000;

2.6.3查询10部门和20部门的员工信息

方法一:(关键字:or)

select * from 表名 别名 where 别名.字段名 = 10 or 别名.字段名 = 20;

方法二:(关键字: in (包含))

select 别名.* from 表名 别名 where 别名.字段名 in(10,20);

2.6.4判断是否为空

判断奖金不为空的员工信息:

SELECT * from 表名 where 字段名 is not null; 
 

2.6.5查询不为0的员工信息(自动过滤null的数据)

SELECT * from 表名 where 字段名 != 0; 

2.5.7查询10部门以外的员工信息:

SELECT * from 表名 where 字段名 not in(10);

2.7模糊查询:(关键字:like)

2.7.1查询员工姓名d开头的

select * from 表名 where 字段名 like 'd%';

2.7.2查询姓名包含d的所有员工信息:

select * from 表名where 字段名 like '%d%';
 

2.7.3查询员工姓名不包含d的信息:

select * from 表名 where 字段名 not like '%d%';

2.8排序(order by、desc、asc):

在sql语句中可以用order by完成数据的排序,还可以通过ASC(升序)、DSC(降序)来制定升序还是降序,默认是按照升序排序

2.8.1查询所有员工信息,工资按照降序排序:

SELECT * from 表名 ORDER BY 字段名; -- 默认升序(ASC)

2.8.2升序查询(关键字 ASC):

SELECT * from 表名 ORDER BY 字段名 ASC;

2.8.3 不等于符号:<>

发布了143 篇原创文章 · 获赞 40 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/LemonSnm/article/details/95303486