赞
踩
MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一。
MySQL是一种关系型数据库管理系统,关系数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性。
MySQL所使用的 SQL 语言是用于访问数据库的最常用标准化语言。MySQL 软件采用了双授权政策,分为社区版和商业版,由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,一般中小型网站的开发都选择 MySQL 作为网站数据库。
与其他的大型数据库例如 Oracle、DB2、SQL Server等相比,MySQL 自有它的不足之处,但是这丝毫也没有减少它受欢迎的程度。对于一般的个人使用者和中小型企业来说,MySQL提供的功能已经绰绰有余,而且由于 MySQL是开放源码软件,因此可以大大降低总体拥有成本。
Linux作为操作系统,Apache 或Nginx作为 Web 服务器,MySQL 作为数据库,PHP/Perl/Python作为服务器端脚本解释器。由于这四个软件都是免费或开放源码软件(FLOSS),因此使用这种方式不用花一分钱(除开人工成本)就可以建立起一个稳定、免费的网站系统,被业界称为“LAMP“或“LNMP”组合。
数据库的优点:
定位:
作用:存储数据的,能够长期(断电或关机在开机数据还有)保存数据。
数据存储在哪里:硬盘和内存
我们平时说的数据库:数据管理系统(软件)(Databases Manage System: DBMS)
数据库软件–>多个数据库(databases)–>多个表(tables)–>多条数据(row,col)(一条一行,一行多列)
特点:
比较常用:
特点:
比较常用:
Redis:一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。(网址:http://www.redis.cn/)
HBase:HBase – Hadoop Database,是一个高可靠性、高性能、面向列、可伸缩的分布式存储系统,利用HBase技术可在廉价PC Server上搭建起大规模结构化存储集群。(网址:https://hbase.apache.org/)
mangoDB:由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。(网址:https://www.mongodb.org.cn/)
neo4j:
结构化查询语言(Structured Query Language)简称SQL,用于存取数据以及查询、更新(数据的操作)和管理(数据库、表的创建、修改、删除)关系数据库系统;
通过SQL语句去操作关系型数据库,不同的数据库对SQL语句的支持不完全一样,85%的SQL语句,关系型数据库都支持。
各个数据库在SQL语句上都有自己的扩展(方言)。
结构化:有行列的数据
非结构化:视频、音乐
刷抖音
抖音APP;短视频通过网络获取,后台有服务器为你提供服务
微信聊天
打开APP,通过网络和别人聊天,在网络之外有服务器提供服务
上淘宝购物
打开浏览器,输入淘宝的网址,后台有服务器为你提供服务
C:Client,客户端
S:Server,服务器
B:Browser:浏览器
C/S:客户端/服务器端
抖音APP/微信APP/手淘APP
B/S:浏览器/服务器端
淘宝网站
注意:B/S是特殊的C/S架构。
总结:一个项目,肯定不单单只有一个APP那么简单。
MySQL其实就一个B/S架构。
使用MySQL步骤:
下载地址:https://dev.mysql.com/downloads/mysql/
本人百度网盘:
链接:https://pan.baidu.com/s/1VPGwI09Uy0DhZHR1pmh5bQ
提取码:asdf
点击.msi文件mysql-5.5.15-win32.msi
接受安装协议
在出现选择安装类型的窗口中,有“typical(默认)”、“Complete(完全)”、“Custom(用户自定义)”三个选项,我们选择“Custom”,因为通过自定义可以选择安装目录,单击“next”继续安装,如图所示:
自定义
install
finish
连续默认点击next,输入root密码
初始化配置点击finish即可
在桌面选择“此电脑”的图标,右键-->属性-->点击“高级系统设置”-->点击“环境变量”。
新建MYSQL_HOME变量,并将值设置为D:\developer_tools\MySQL。
编辑Path系统变量:在系统变量里,找到Path变量,点击“编辑”按钮,将;%MYSQL_HOME%\bin添加到path变量(一般放在最后面),注意如果前面有还有其他的配置,一定要在前面加上英文的分号(半角)。
方式一:计算机——右击管理——服务
方式二:通过管理员身份运行
net start 服务名(启动服务)
net stop 服务名(停止服务)
启动命令终端: Win + R–>输入cmd–>回车
启动MySQL服务:net start mysql
关闭MySQL服务:net stop mysql
方式一:通过mysql自带的客户端
只限于root用户
方式二:通过windows自带的客户端
登录:
mysql 【-h主机名 -P端口号 】-u用户名 -p密码
命令行 mysql -u root -p
-u:user:用户名 root(超级管理员)
-p:password:密码
-h:hostname主机名(ip)
-P:Port端口
在服务中将mysql数据库启动,并在命令窗口中输入“mysql –h localhost –u root -p”,接着在出现的提示中输入用户的密码
cmd:(password为安装时root的密码)
退出:
exit或ctrl+C
下载地址:https://dev.mysql.com/downloads/mysql/
本人百度网盘:
链接:https://pan.baidu.com/s/1VPGwI09Uy0DhZHR1pmh5bQ
提取码:asdf
检测是否安装MySQL
- [hadoop@hadoop10 installPkg]$ rpm -qa | grep -i mysql
- mysql-libs-5.1.71-1.el6.x86_64
卸载自带的MySQL
[hadoop@hadoop10 installPkg]$ sudo rpm -e --nodeps mysql-libs-5.1.71-1.el6.x86_64
将安装包上传服务器installPkg目录下。
安装MySQL服务。我们需要将MySQL做成系统服务,开机启动。需要root
[hadoop@hadoop10 installPkg]$ sudo rpm -ivh MySQL-server-5.5.28-1.linux2.6.x86_64.rpm
PLEASE REMEMBER TO SET A PASSWORD FOR
THE MySQL root USER ! To do so, start the server,
then issue the following commands:
/usr/bin/mysqladmin -u root password 'new-
password' /usr/bin/mysqladmin -u root -h
hadoop10 password 'new-password'
Alternatively you can run:
/usr/bin/mysql_secure_installation
which will also give you the option of removing
the test databases and anonymous user created
by default. This is strongly recommended for
production servers.
See the manual for more instructions.
Please report any problems with the
/usr/bin/mysqlbug script!
安装MySQL客户端
[hadoop@hadoop10 installPkg]$ sudo rpm -ivh MySQL-client-5.5.28-1.linux2.6.x86_64.rpm
启动MySQL服务
- [hadoop@hadoop10 installPkg]$ sudo service mysql start
- Starting MySQL..
- [ OK ]
- [hadoop@hadoop10 installPkg]$ sudo service mysql status
- MySQL running (6266)
- [ OK ]
- [hadoop@hadoop10 installPkg]$ sudo chkconfig mysql on
运行脚本
[hadoop@hadoop10 installPkg]$/usr/bin/mysql_secure_installation
Set root password? [Y/n] y New password: Re-
enter new password: Password updated
successfully! Reloading privilege tables.. ...
Success!
Remove anonymous users? [Y/n] y ... Success!Disallow root login remotely? [Y/n] n ... skipping.
Remove test database and access to it? [Y/n] y
Dropping test database... ... Success!
Removing privileges on test database... ...
Success!
Reload privilege tables now? [Y/n] y ... Success!
.........
Thanks for using MySQL!
无主机登录(远程登录的授权)
方式一:
在命令窗口中输入“mysql –h localhost –u root -p”
- mysql> show databases;
- mysql> use mysql;
- mysql> show tables;
- mysql> select Host,User,Password from user;
- mysql> update user set Host="%" where Host="localhost";
- mysql> delete from user where Host != "%";
- mysql> flush privileges;
方式二:
- mysql> grant all privileges on *.* to "root"@"%" identified by "你的密码";
- mysql> flush privileges;
navicat premium、SQLyog
navicat premium官网:https://www.navicat.com.cn/
SQLyog下载地址:https://sqlyog.en.softonic.com/download
本人网盘:
运行SQLyog-13.1.6-0.x64Community.exe
选择语言
单击“下一步”
接受“许可证协议”
单击“下一步”
选择安装位置
“下一步”
完成
选择语言
运行应用
创建连接
连接
navicat下载地址:https://www.navicat.com.cn/download/navicat-premium
或https://www.navicat.com/en/download/navicat-premium
运行navicat150_premium_cs_x64.exe
点击“下一步”
同意许可证
选择安装目录
选择创建快捷方式的目录
“下一步”
安装
等待安装
完成
进入应用
创建连接
测试连接
连接
1.查看当前所有的数据库
show databases;
2.打开指定的库
use 库名;
3.查看当前库的所有表
show tables;
4.查看其它库的所有表
show tables from 库名;
5.创建表
create table 表名(列名 列类型,
列名 列类型,
。。。
);
6. 查看指定表的结构
desc 表名;7. 显示表中的所有数据
select * from 表名;8.查看服务器的版本
方式一:登录到mysql服务端
select version();
方式二:没有登录到mysql服务端
mysql --version
或
mysql --V
单行注释:#注释文字
单行注释:-- 注释文字
多行注释:/* 注释文字 */
DQL(Data Query Language):数据查询语言 如:select
DML(Data Manipulate Language):数据操作语言 如:insert、update、delete
DDL(Data Define Languge):数据定义语言 如:create、drop、alter
TCL(Transaction Control Language):事务控制语言 如:commit、rollback
Database:数据库
Table:表格
Row:行;多少行
Field:字段;列
Type:类型
Key:钥匙;键
Show:展示;查看
Query:查询
Create:创建
Modify:修改
Update:更新
Alter:修改
Remove:移除,删除
Drop:删除
Where:在条件;条件
Date:日期
Data:数据
在写sql语句时必不可少的是记事本,这对于写语句,校验,存储sql,都有很大有用处,直接在命令行中打一连串的命令有些不现实。
这里推荐用 Nodepad++
使用:
直接上SQL:myemployees.sql
创建库:myemployees;创建表:departments、employees、jobs、locations。
- /*
- MySQL - 5.5.15 : Database - myemployees
- *********************************************************************
- */
-
- /*!40101 SET NAMES utf8 */;
-
- CREATE DATABASE IF NOT EXISTS`myemployees` /*!40100 DEFAULT CHARACTER SET gb2312 */;
-
- USE `myemployees`;
-
- /*Table structure for table `departments` */
-
- DROP TABLE IF EXISTS `departments`;
-
- CREATE TABLE `departments` (
- `department_id` int(4) NOT NULL AUTO_INCREMENT,
- `department_name` varchar(3) DEFAULT NULL,
- `manager_id` int(6) DEFAULT NULL,
- `location_id` int(4) DEFAULT NULL,
- PRIMARY KEY (`department_id`),
- KEY `loc_id_fk` (`location_id`),
- CONSTRAINT `loc_id_fk` FOREIGN KEY (`location_id`) REFERENCES `locations` (`location_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=271 DEFAULT CHARSET=gb2312;
-
- /*Data for the table `departments` */
-
- insert into `departments`(`department_id`,`department_name`,`manager_id`,`location_id`) values (10,'Adm',200,1700),(20,'Mar',201,1800),(30,'Pur',114,1700),(40,'Hum',203,2400),(50,'Shi',121,1500),(60,'IT',103,1400),(70,'Pub',204,2700),(80,'Sal',145,2500),(90,'Exe',100,1700),(100,'Fin',108,1700),(110,'Acc',205,1700),(120,'Tre',NULL,1700),(130,'Cor',NULL,1700),(140,'Con',NULL,1700),(150,'Sha',NULL,1700),(160,'Ben',NULL,1700),(170,'Man',NULL,1700),(180,'Con',NULL,1700),(190,'Con',NULL,1700),(200,'Ope',NULL,1700),(210,'IT ',NULL,1700),(220,'NOC',NULL,1700),(230,'IT ',NULL,1700),(240,'Gov',NULL,1700),(250,'Ret',NULL,1700),(260,'Rec',NULL,1700),(270,'Pay',NULL,1700);
-
- /*Table structure for table `employees` */
-
- DROP TABLE IF EXISTS `employees`;
-
- CREATE TABLE `employees` (
- `employee_id` int(6) NOT NULL AUTO_INCREMENT,
- `first_name` varchar(20) DEFAULT NULL,
- `last_name` varchar(25) DEFAULT NULL,
- `email` varchar(25) DEFAULT NULL,
- `phone_number` varchar(20) DEFAULT NULL,
- `job_id` varchar(10) DEFAULT NULL,
- `salary` double(10,2) DEFAULT NULL,
- `commission_pct` double(4,2) DEFAULT NULL,
- `manager_id` int(6) DEFAULT NULL,
- `department_id` int(4) DEFAULT NULL,
- `hiredate` datetime DEFAULT NULL,
- PRIMARY KEY (`employee_id`),
- KEY `dept_id_fk` (`department_id`),
- KEY `job_id_fk` (`job_id`),
- CONSTRAINT `dept_id_fk` FOREIGN KEY (`department_id`) REFERENCES `departments` (`department_id`),
- CONSTRAINT `job_id_fk` FOREIGN KEY (`job_id`) REFERENCES `jobs` (`job_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=207 DEFAULT CHARSET=gb2312;
-
- /*Data for the table `employees` */
-
- insert into `employees`(`employee_id`,`first_name`,`last_name`,`email`,`phone_number`,`job_id`,`salary`,`commission_pct`,`manager_id`,`department_id`,`hiredate`) values (100,'Steven','K_ing','SKING','515.123.4567','AD_PRES',24000.00,NULL,NULL,90,'1992-04-03 00:00:00'),(101,'Neena','Kochhar','NKOCHHAR','515.123.4568','AD_VP',17000.00,NULL,100,90,'1992-04-03 00:00:00'),(102,'Lex','De Haan','LDEHAAN','515.123.4569','AD_VP',17000.00,NULL,100,90,'1992-04-03 00:00:00'),(103,'Alexander','Hunold','AHUNOLD','590.423.4567','IT_PROG',9000.00,NULL,102,60,'1992-04-03 00:00:00'),(104,'Bruce','Ernst','BERNST','590.423.4568','IT_PROG',6000.00,NULL,103,60,'1992-04-03 00:00:00'),(105,'David','Austin','DAUSTIN','590.423.4569','IT_PROG',4800.00,NULL,103,60,'1998-03-03 00:00:00'),(106,'Valli','Pataballa','VPATABAL','590.423.4560','IT_PROG',4800.00,NULL,103,60,'1998-03-03 00:00:00'),(107,'Diana','Lorentz','DLORENTZ','590.423.5567','IT_PROG',4200.00,NULL,103,60,'1998-03-03 00:00:00'),(108,'Nancy','Greenberg','NGREENBE','515.124.4569','FI_MGR',12000.00,NULL,101,100,'1998-03-03 00:00:00'),(109,'Daniel','Faviet','DFAVIET','515.124.4169','FI_ACCOUNT',9000.00,NULL,108,100,'1998-03-03 00:00:00'),(110,'John','Chen','JCHEN','515.124.4269','FI_ACCOUNT',8200.00,NULL,108,100,'2000-09-09 00:00:00'),(111,'Ismael','Sciarra','ISCIARRA','515.124.4369','FI_ACCOUNT',7700.00,NULL,108,100,'2000-09-09 00:00:00'),(112,'Jose Manuel','Urman','JMURMAN','515.124.4469','FI_ACCOUNT',7800.00,NULL,108,100,'2000-09-09 00:00:00'),(113,'Luis','Popp','LPOPP','515.124.4567','FI_ACCOUNT',6900.00,NULL,108,100,'2000-09-09 00:00:00'),(114,'Den','Raphaely','DRAPHEAL','515.127.4561','PU_MAN',11000.00,NULL,100,30,'2000-09-09 00:00:00'),(115,'Alexander','Khoo','AKHOO','515.127.4562','PU_CLERK',3100.00,NULL,114,30,'2000-09-09 00:00:00'),(116,'Shelli','Baida','SBAIDA','515.127.4563','PU_CLERK',2900.00,NULL,114,30,'2000-09-09 00:00:00'),(117,'Sigal','Tobias','STOBIAS','515.127.4564','PU_CLERK',2800.00,NULL,114,30,'2000-09-09 00:00:00'),(118,'Guy','Himuro','GHIMURO','515.127.4565','PU_CLERK',2600.00,NULL,114,30,'2000-09-09 00:00:00'),(119,'Karen','Colmenares','KCOLMENA','515.127.4566','PU_CLERK',2500.00,NULL,114,30,'2000-09-09 00:00:00'),(120,'Matthew','Weiss','MWEISS','650.123.1234','ST_MAN',8000.00,NULL,100,50,'2004-02-06 00:00:00'),(121,'Adam','Fripp','AFRIPP','650.123.2234','ST_MAN',8200.00,NULL,100,50,'2004-02-06 00:00:00'),(122,'Payam','Kaufling','PKAUFLIN','650.123.3234','ST_MAN',7900.00,NULL,100,50,'2004-02-06 00:00:00'),(123,'Shanta','Vollman','SVOLLMAN','650.123.4234','ST_MAN',6500.00,NULL,100,50,'2004-02-06 00:00:00'),(124,'Kevin','Mourgos','KMOURGOS','650.123.5234','ST_MAN',5800.00,NULL,100,50,'2004-02-06 00:00:00'),(125,'Julia','Nayer','JNAYER','650.124.1214','ST_CLERK',3200.00,NULL,120,50,'2004-02-06 00:00:00'),(126,'Irene','Mikkilineni','IMIKKILI','650.124.1224','ST_CLERK',2700.00,NULL,120,50,'2004-02-06 00:00:00'),(127,'James','Landry','JLANDRY','650.124.1334','ST_CLERK',2400.00,NULL,120,50,'2004-02-06 00:00:00'),(128,'Steven','Markle','SMARKLE','650.124.1434','ST_CLERK',2200.00,NULL,120,50,'2004-02-06 00:00:00'),(129,'Laura','Bissot','LBISSOT','650.124.5234','ST_CLERK',3300.00,NULL,121,50,'2004-02-06 00:00:00'),(130,'Mozhe','Atkinson','MATKINSO','650.124.6234','ST_CLERK',2800.00,NULL,121,50,'2004-02-06 00:00:00'),(131,'James','Marlow','JAMRLOW','650.124.7234','ST_CLERK',2500.00,NULL,121,50,'2004-02-06 00:00:00'),(132,'TJ','Olson','TJOLSON','650.124.8234','ST_CLERK',2100.00,NULL,121,50,'2004-02-06 00:00:00'),(133,'Jason','Mallin','JMALLIN','650.127.1934','ST_CLERK',3300.00,NULL,122,50,'2004-02-06 00:00:00'),(134,'Michael','Rogers','MROGERS','650.127.1834','ST_CLERK',2900.00,NULL,122,50,'2002-12-23 00:00:00'),(135,'Ki','Gee','KGEE','650.127.1734','ST_CLERK',2400.00,NULL,122,50,'2002-12-23 00:00:00'),(136,'Hazel','Philtanker','HPHILTAN','650.127.1634','ST_CLERK',2200.00,NULL,122,50,'2002-12-23 00:00:00'),(137,'Renske','Ladwig','RLADWIG','650.121.1234','ST_CLERK',3600.00,NULL,123,50,'2002-12-23 00:00:00'),(138,'Stephen','Stiles','SSTILES','650.121.2034','ST_CLERK',3200.00,NULL,123,50,'2002-12-23 00:00:00'),(139,'John','Seo','JSEO','650.121.2019','ST_CLERK',2700.00,NULL,123,50,'2002-12-23 00:00:00'),(140,'Joshua','Patel','JPATEL','650.121.1834','ST_CLERK',2500.00,NULL,123,50,'2002-12-23 00:00:00'),(141,'Trenna','Rajs','TRAJS','650.121.8009','ST_CLERK',3500.00,NULL,124,50,'2002-12-23 00:00:00'),(142,'Curtis','Davies','CDAVIES','650.121.2994','ST_CLERK',3100.00,NULL,124,50,'2002-12-23 00:00:00'),(143,'Randall','Matos','RMATOS','650.121.2874','ST_CLERK',2600.00,NULL,124,50,'2002-12-23 00:00:00'),(144,'Peter','Vargas','PVARGAS','650.121.2004','ST_CLERK',2500.00,NULL,124,50,'2002-12-23 00:00:00'),(145,'John','Russell','JRUSSEL','011.44.1344.429268','SA_MAN',14000.00,0.40,100,80,'2002-12-23 00:00:00'),(146,'Karen','Partners','KPARTNER','011.44.1344.467268','SA_MAN',13500.00,0.30,100,80,'2002-12-23 00:00:00'),(147,'Alberto','Errazuriz','AERRAZUR','011.44.1344.429278','SA_MAN',12000.00,0.30,100,80,'2002-12-23 00:00:00'),(148,'Gerald','Cambrault','GCAMBRAU','011.44.1344.619268','SA_MAN',11000.00,0.30,100,80,'2002-12-23 00:00:00'),(149,'Eleni','Zlotkey','EZLOTKEY','011.44.1344.429018','SA_MAN',10500.00,0.20,100,80,'2002-12-23 00:00:00'),(150,'Peter','Tucker','PTUCKER','011.44.1344.129268','SA_REP',10000.00,0.30,145,80,'2014-03-05 00:00:00'),(151,'David','Bernstein','DBERNSTE','011.44.1344.345268','SA_REP',9500.00,0.25,145,80,'2014-03-05 00:00:00'),(152,'Peter','Hall','PHALL','011.44.1344.478968','SA_REP',9000.00,0.25,145,80,'2014-03-05 00:00:00'),(153,'Christopher','Olsen','COLSEN','011.44.1344.498718','SA_REP',8000.00,0.20,145,80,'2014-03-05 00:00:00'),(154,'Nanette','Cambrault','NCAMBRAU','011.44.1344.987668','SA_REP',7500.00,0.20,145,80,'2014-03-05 00:00:00'),(155,'Oliver','Tuvault','OTUVAULT','011.44.1344.486508','SA_REP',7000.00,0.15,145,80,'2014-03-05 00:00:00'),(156,'Janette','K_ing','JKING','011.44.1345.429268','SA_REP',10000.00,0.35,146,80,'2014-03-05 00:00:00'),(157,'Patrick','Sully','PSULLY','011.44.1345.929268','SA_REP',9500.00,0.35,146,80,'2014-03-05 00:00:00'),(158,'Allan','McEwen','AMCEWEN','011.44.1345.829268','SA_REP',9000.00,0.35,146,80,'2014-03-05 00:00:00'),(159,'Lindsey','Smith','LSMITH','011.44.1345.729268','SA_REP',8000.00,0.30,146,80,'2014-03-05 00:00:00'),(160,'Louise','Doran','LDORAN','011.44.1345.629268','SA_REP',7500.00,0.30,146,80,'2014-03-05 00:00:00'),(161,'Sarath','Sewall','SSEWALL','011.44.1345.529268','SA_REP',7000.00,0.25,146,80,'2014-03-05 00:00:00'),(162,'Clara','Vishney','CVISHNEY','011.44.1346.129268','SA_REP',10500.00,0.25,147,80,'2014-03-05 00:00:00'),(163,'Danielle','Greene','DGREENE','011.44.1346.229268','SA_REP',9500.00,0.15,147,80,'2014-03-05 00:00:00'),(164,'Mattea','Marvins','MMARVINS','011.44.1346.329268','SA_REP',7200.00,0.10,147,80,'2014-03-05 00:00:00'),(165,'David','Lee','DLEE','011.44.1346.529268','SA_REP',6800.00,0.10,147,80,'2014-03-05 00:00:00'),(166,'Sundar','Ande','SANDE','011.44.1346.629268','SA_REP',6400.00,0.10,147,80,'2014-03-05 00:00:00'),(167,'Amit','Banda','ABANDA','011.44.1346.729268','SA_REP',6200.00,0.10,147,80,'2014-03-05 00:00:00'),(168,'Lisa','Ozer','LOZER','011.44.1343.929268','SA_REP',11500.00,0.25,148,80,'2014-03-05 00:00:00'),(169,'Harrison','Bloom','HBLOOM','011.44.1343.829268','SA_REP',10000.00,0.20,148,80,'2014-03-05 00:00:00'),(170,'Tayler','Fox','TFOX','011.44.1343.729268','SA_REP',9600.00,0.20,148,80,'2014-03-05 00:00:00'),(171,'William','Smith','WSMITH','011.44.1343.629268','SA_REP',7400.00,0.15,148,80,'2014-03-05 00:00:00'),(172,'Elizabeth','Bates','EBATES','011.44.1343.529268','SA_REP',7300.00,0.15,148,80,'2014-03-05 00:00:00'),(173,'Sundita','Kumar','SKUMAR','011.44.1343.329268','SA_REP',6100.00,0.10,148,80,'2014-03-05 00:00:00'),(174,'Ellen','Abel','EABEL','011.44.1644.429267','SA_REP',11000.00,0.30,149,80,'2014-03-05 00:00:00'),(175,'Alyssa','Hutton','AHUTTON','011.44.1644.429266','SA_REP',8800.00,0.25,149,80,'2014-03-05 00:00:00'),(176,'Jonathon','Taylor','JTAYLOR','011.44.1644.429265','SA_REP',8600.00,0.20,149,80,'2014-03-05 00:00:00'),(177,'Jack','Livingston','JLIVINGS','011.44.1644.429264','SA_REP',8400.00,0.20,149,80,'2014-03-05 00:00:00'),(178,'Kimberely','Grant','KGRANT','011.44.1644.429263','SA_REP',7000.00,0.15,149,NULL,'2014-03-05 00:00:00'),(179,'Charles','Johnson','CJOHNSON','011.44.1644.429262','SA_REP',6200.00,0.10,149,80,'2014-03-05 00:00:00'),(180,'Winston','Taylor','WTAYLOR','650.507.9876','SH_CLERK',3200.00,NULL,120,50,'2014-03-05 00:00:00'),(181,'Jean','Fleaur','JFLEAUR','650.507.9877','SH_CLERK',3100.00,NULL,120,50,'2014-03-05 00:00:00'),(182,'Martha','Sullivan','MSULLIVA','650.507.9878','SH_CLERK',2500.00,NULL,120,50,'2014-03-05 00:00:00'),(183,'Girard','Geoni','GGEONI','650.507.9879','SH_CLERK',2800.00,NULL,120,50,'2014-03-05 00:00:00'),(184,'Nandita','Sarchand','NSARCHAN','650.509.1876','SH_CLERK',4200.00,NULL,121,50,'2014-03-05 00:00:00'),(185,'Alexis','Bull','ABULL','650.509.2876','SH_CLERK',4100.00,NULL,121,50,'2014-03-05 00:00:00'),(186,'Julia','Dellinger','JDELLING','650.509.3876','SH_CLERK',3400.00,NULL,121,50,'2014-03-05 00:00:00'),(187,'Anthony','Cabrio','ACABRIO','650.509.4876','SH_CLERK',3000.00,NULL,121,50,'2014-03-05 00:00:00'),(188,'Kelly','Chung','KCHUNG','650.505.1876','SH_CLERK',3800.00,NULL,122,50,'2014-03-05 00:00:00'),(189,'Jennifer','Dilly','JDILLY','650.505.2876','SH_CLERK',3600.00,NULL,122,50,'2014-03-05 00:00:00'),(190,'Timothy','Gates','TGATES','650.505.3876','SH_CLERK',2900.00,NULL,122,50,'2014-03-05 00:00:00'),(191,'Randall','Perkins','RPERKINS','650.505.4876','SH_CLERK',2500.00,NULL,122,50,'2014-03-05 00:00:00'),(192,'Sarah','Bell','SBELL','650.501.1876','SH_CLERK',4000.00,NULL,123,50,'2014-03-05 00:00:00'),(193,'Britney','Everett','BEVERETT','650.501.2876','SH_CLERK',3900.00,NULL,123,50,'2014-03-05 00:00:00'),(194,'Samuel','McCain','SMCCAIN','650.501.3876','SH_CLERK',3200.00,NULL,123,50,'2014-03-05 00:00:00'),(195,'Vance','Jones','VJONES','650.501.4876','SH_CLERK',2800.00,NULL,123,50,'2014-03-05 00:00:00'),(196,'Alana','Walsh','AWALSH','650.507.9811','SH_CLERK',3100.00,NULL,124,50,'2014-03-05 00:00:00'),(197,'Kevin','Feeney','KFEENEY','650.507.9822','SH_CLERK',3000.00,NULL,124,50,'2014-03-05 00:00:00'),(198,'Donald','OConnell','DOCONNEL','650.507.9833','SH_CLERK',2600.00,NULL,124,50,'2014-03-05 00:00:00'),(199,'Douglas','Grant','DGRANT','650.507.9844','SH_CLERK',2600.00,NULL,124,50,'2014-03-05 00:00:00'),(200,'Jennifer','Whalen','JWHALEN','515.123.4444','AD_ASST',4400.00,NULL,101,10,'2016-03-03 00:00:00'),(201,'Michael','Hartstein','MHARTSTE','515.123.5555','MK_MAN',13000.00,NULL,100,20,'2016-03-03 00:00:00'),(202,'Pat','Fay','PFAY','603.123.6666','MK_REP',6000.00,NULL,201,20,'2016-03-03 00:00:00'),(203,'Susan','Mavris','SMAVRIS','515.123.7777','HR_REP',6500.00,NULL,101,40,'2016-03-03 00:00:00'),(204,'Hermann','Baer','HBAER','515.123.8888','PR_REP',10000.00,NULL,101,70,'2016-03-03 00:00:00'),(205,'Shelley','Higgins','SHIGGINS','515.123.8080','AC_MGR',12000.00,NULL,101,110,'2016-03-03 00:00:00'),(206,'William','Gietz','WGIETZ','515.123.8181','AC_ACCOUNT',8300.00,NULL,205,110,'2016-03-03 00:00:00');
-
- /*Table structure for table `jobs` */
-
- DROP TABLE IF EXISTS `jobs`;
-
- CREATE TABLE `jobs` (
- `job_id` varchar(10) NOT NULL,
- `job_title` varchar(35) DEFAULT NULL,
- `min_salary` int(6) DEFAULT NULL,
- `max_salary` int(6) DEFAULT NULL,
- PRIMARY KEY (`job_id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
-
- /*Data for the table `jobs` */
-
- insert into `jobs`(`job_id`,`job_title`,`min_salary`,`max_salary`) values ('AC_ACCOUNT','Public Accountant',4200,9000),('AC_MGR','Accounting Manager',8200,16000),('AD_ASST','Administration Assistant',3000,6000),('AD_PRES','President',20000,40000),('AD_VP','Administration Vice President',15000,30000),('FI_ACCOUNT','Accountant',4200,9000),('FI_MGR','Finance Manager',8200,16000),('HR_REP','Human Resources Representative',4000,9000),('IT_PROG','Programmer',4000,10000),('MK_MAN','Marketing Manager',9000,15000),('MK_REP','Marketing Representative',4000,9000),('PR_REP','Public Relations Representative',4500,10500),('PU_CLERK','Purchasing Clerk',2500,5500),('PU_MAN','Purchasing Manager',8000,15000),('SA_MAN','Sales Manager',10000,20000),('SA_REP','Sales Representative',6000,12000),('SH_CLERK','Shipping Clerk',2500,5500),('ST_CLERK','Stock Clerk',2000,5000),('ST_MAN','Stock Manager',5500,8500);
-
- /*Table structure for table `locations` */
-
- DROP TABLE IF EXISTS `locations`;
-
- CREATE TABLE `locations` (
- `location_id` int(11) NOT NULL AUTO_INCREMENT,
- `street_address` varchar(40) DEFAULT NULL,
- `postal_code` varchar(12) DEFAULT NULL,
- `city` varchar(30) DEFAULT NULL,
- `state_province` varchar(25) DEFAULT NULL,
- `country_id` varchar(2) DEFAULT NULL,
- PRIMARY KEY (`location_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=3201 DEFAULT CHARSET=gb2312;
-
- /*Data for the table `locations` */
-
- insert into `locations`(`location_id`,`street_address`,`postal_code`,`city`,`state_province`,`country_id`) values (1000,'1297 Via Cola di Rie','00989','Roma',NULL,'IT'),(1100,'93091 Calle della Testa','10934','Venice',NULL,'IT'),(1200,'2017 Shinjuku-ku','1689','Tokyo','Tokyo Prefecture','JP'),(1300,'9450 Kamiya-cho','6823','Hiroshima',NULL,'JP'),(1400,'2014 Jabberwocky Rd','26192','Southlake','Texas','US'),(1500,'2011 Interiors Blvd','99236','South San Francisco','California','US'),(1600,'2007 Zagora St','50090','South Brunswick','New Jersey','US'),(1700,'2004 Charade Rd','98199','Seattle','Washington','US'),(1800,'147 Spadina Ave','M5V 2L7','Toronto','Ontario','CA'),(1900,'6092 Boxwood St','YSW 9T2','Whitehorse','Yukon','CA'),(2000,'40-5-12 Laogianggen','190518','Beijing',NULL,'CN'),(2100,'1298 Vileparle (E)','490231','Bombay','Maharashtra','IN'),(2200,'12-98 Victoria Street','2901','Sydney','New South Wales','AU'),(2300,'198 Clementi North','540198','Singapore',NULL,'SG'),(2400,'8204 Arthur St',NULL,'London',NULL,'UK'),(2500,'Magdalen Centre, The Oxford Science Park','OX9 9ZB','Oxford','Oxford','UK'),(2600,'9702 Chester Road','09629850293','Stretford','Manchester','UK'),(2700,'Schwanthalerstr. 7031','80925','Munich','Bavaria','DE'),(2800,'Rua Frei Caneca 1360 ','01307-002','Sao Paulo','Sao Paulo','BR'),(2900,'20 Rue des Corps-Saints','1730','Geneva','Geneve','CH'),(3000,'Murtenstrasse 921','3095','Bern','BE','CH'),(3100,'Pieter Breughelstraat 837','3029SK','Utrecht','Utrecht','NL'),(3200,'Mariano Escobedo 9991','11932','Mexico City','Distrito Federal,','MX');
-
-
直接上SQL:girls.sql
创建库:girls;创建表:admin、beauty、boys。
- /*
- MySQL - 5.7.18-log : Database - girls
- *********************************************************************
- */
-
- /*!40101 SET NAMES utf8 */;
-
- CREATE DATABASE /*!32312 IF NOT EXISTS*/`girls` /*!40100 DEFAULT CHARACTER SET utf8 */;
-
- USE `girls`;
-
- /*Table structure for table `admin` */
-
- DROP TABLE IF EXISTS `admin`;
-
- CREATE TABLE `admin` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `username` varchar(10) NOT NULL,
- `password` varchar(10) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-
- /*Data for the table `admin` */
-
- insert into `admin`(`id`,`username`,`password`) values (1,'john','8888'),(2,'lyt','6666');
-
- /*Table structure for table `beauty` */
-
- DROP TABLE IF EXISTS `beauty`;
-
- CREATE TABLE `beauty` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(50) NOT NULL,
- `sex` char(1) DEFAULT '女',
- `borndate` datetime DEFAULT '1987-01-01 00:00:00',
- `phone` varchar(11) NOT NULL,
- `photo` blob,
- `boyfriend_id` int(11) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
-
- /*Data for the table `beauty` */
-
- insert into `beauty`(`id`,`name`,`sex`,`borndate`,`phone`,`photo`,`boyfriend_id`) values (1,'柳岩','女','1988-02-03 00:00:00','18209876577',NULL,8),(2,'苍老师','女','1987-12-30 00:00:00','18219876577',NULL,9),(3,'Angelababy','女','1989-02-03 00:00:00','18209876567',NULL,3),(4,'热巴','女','1993-02-03 00:00:00','18209876579',NULL,2),(5,'周冬雨','女','1992-02-03 00:00:00','18209179577',NULL,9),(6,'周芷若','女','1988-02-03 00:00:00','18209876577',NULL,1),(7,'岳灵珊','女','1987-12-30 00:00:00','18219876577',NULL,9),(8,'小昭','女','1989-02-03 00:00:00','18209876567',NULL,1),(9,'双儿','女','1993-02-03 00:00:00','18209876579',NULL,9),(10,'王语嫣','女','1992-02-03 00:00:00','18209179577',NULL,4),(11,'夏雪','女','1993-02-03 00:00:00','18209876579',NULL,9),(12,'赵敏','女','1992-02-03 00:00:00','18209179577',NULL,1);
-
- /*Table structure for table `boys` */
-
- DROP TABLE IF EXISTS `boys`;
-
- CREATE TABLE `boys` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `boyName` varchar(20) DEFAULT NULL,
- `userCP` int(11) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-
- /*Data for the table `boys` */
-
- insert into `boys`(`id`,`boyName`,`userCP`) values (1,'张无忌',100),(2,'鹿晗',800),(3,'黄晓明',50),(4,'段誉',300);
-
语法:
select 查询列表 from 表名;
特点:
选择库:
USE myemployees;
查询表中的单个字段
SELECT last_name FROM employees;
查询表中的多个字段
SELECT last_name,salary,email FROM employees;
查询表中的所有字段
- #方式一:
- SELECT
- `employee_id`,
- `first_name`,
- `last_name`,
- `phone_number`,
- `last_name`,
- `job_id`,
- `phone_number`,
- `job_id`,
- `salary`,
- `commission_pct`,
- `manager_id`,
- `department_id`,
- `hiredate`
- FROM
- employees ;
- #方式二:
- SELECT * FROM employees;
查询常量值
- SELECT 150;
- SELECT 'tom';
查询表达式
SELECT 100%2;
查询函数
SELECT VERSION();
起别名
①便于理解
②如果要查询的字段有重名的情况,使用别名可以区分开来
- #方式一:使用as
- SELECT 100%2 AS 结果;
- SELECT last_name AS 姓,first_name AS 名 FROM employees;
-
- #方式二:使用空格
- SELECT last_name 姓,first_name 名 FROM employees;
-
- #案例:查询salary,显示结果为 out put
- SELECT salary AS "out put" FROM employees;
去重
- #案例:查询员工表中涉及到的所有的部门编号
- SELECT DISTINCT department_id FROM employees;
+号的作用
java中的+号:
①运算符,两个操作数都为数值型
②连接符,只要有一个操作数为字符串mysql中的+号:
仅仅只有一个功能:运算符select 100+90; 两个操作数都为数值型,则做加法运算
select '123'+90;只要其中一方为字符型,试图将字符型数值转换成数值型
如果转换成功,则继续做加法运算
select 'john'+90; 如果转换失败,则将字符型数值转换成0select null+10; 只要其中一方为null,则结果肯定为null
- #案例:查询员工名和姓连接成一个字段,并显示为 姓名
-
- SELECT CONCAT('a','b','c') AS '结果';
-
- SELECT
- CONCAT(last_name,first_name) AS 姓名
- FROM
- employees;
select
查询列表
from
表名
where
筛选条件;
1)按条件表达式筛选
简单条件运算符:> < = != <> >= <=
2)按逻辑表达式筛选
逻辑运算符:
作用:用于连接条件表达式
&& || !
and or not
&&和and:两个条件都为true,结果为true,反之为false
||或or: 只要有一个条件为true,结果为true,反之为false
!或not: 如果连接的条件本身为false,结果为true,反之为false
3)模糊查询
like
between and
in
is null
按条件表达式筛选
案例1:查询工资>12000的员工信息
- SELECT
- *
- FROM
- employees
- WHERE
- salary>12000;
案例2:查询部门编号不等于90号的员工名和部门编号
- SELECT
- last_name,
- department_id
- FROM
- employees
- WHERE
- department_id<>90;
按逻辑表达式筛选
案例1:查询工资z在10000到20000之间的员工名、工资以及奖金
- SELECT
- last_name,
- salary,
- commission_pct
- FROM
- employees
- WHERE
- salary>=10000 AND salary<=20000;
案例2:查询部门编号不是在90到110之间,或者工资高于15000的员工信息
- SELECT
- *
- FROM
- employees
- WHERE
- NOT(department_id>=90 AND department_id<=110) OR salary>15000;
模糊查询
like
between and
in
is null|is not null
1.like
特点:
①一般和通配符搭配使用
通配符:
% 任意多个字符,包含0个字符
_ 任意单个字符
案例1:查询员工名中包含字符a的员工信息
- select
- *
- from
- employees
- where
- last_name like '%a%';#abc
案例2:查询员工名中第三个字符为n,第五个字符为l的员工名和工资
- select
- last_name,
- salary
- FROM
- employees
- WHERE
- last_name LIKE '__n_l%';
案例3:查询员工名中第二个字符为_的员工名
- SELECT
- last_name
- FROM
- employees
- WHERE
- last_name LIKE '_$_%' ESCAPE '$';
2.between and
①使用between and 可以提高语句的简洁度
②包含临界值
③两个临界值不要调换顺序
案例:查询员工编号在100到120之间的员工信息
- SELECT
- *
- FROM
- employees
- WHERE
- employee_id >= 120 AND employee_id<=100;
- #----------------------
- SELECT
- *
- FROM
- employees
- WHERE
- employee_id BETWEEN 120 AND 100;
3.in
含义:判断某字段的值是否属于in列表中的某一项
特点:
①使用in提高语句简洁度
②in列表的值类型必须一致或兼容
③in列表中不支持通配符
案例:查询员工的工种编号是 IT_PROG、AD_VP、AD_PRES中的一个员工名和工种编号
- SELECT
- last_name,
- job_id
- FROM
- employees
- WHERE
- job_id = 'IT_PROT' OR job_id = 'AD_VP' OR job_id ='AD_PRES';
- #------------------
-
- SELECT
- last_name,
- job_id
- FROM
- employees
- WHERE
- job_id IN( 'IT_PROT' ,'AD_VP','AD_PRES');
4.is null
=或<>不能用于判断null值
is null或is not null 可以判断null值
案例1:查询没有奖金的员工名和奖金率
- SELECT
- last_name,
- commission_pct
- FROM
- employees
- WHERE
- commission_pct IS NULL;
案例2:查询有奖金的员工名和奖金率
- SELECT
- last_name,
- commission_pct
- FROM
- employees
- WHERE
- commission_pct IS NOT NULL;
-
- #----------以下为is
- SELECT
- last_name,
- commission_pct
- FROM
- employees
-
- WHERE
- salary IS 12000;
安全等于 <=>
案例1:查询没有奖金的员工名和奖金率
- SELECT
- last_name,
- commission_pct
- FROM
- employees
- WHERE
- commission_pct <=>NULL;
案例2:查询工资为12000的员工信息
- SELECT
- last_name,
- salary
- FROM
- employees
-
- WHERE
- salary <=> 12000;
is null VS <=>
IS NULL:仅仅可以判断NULL值,可读性较高,建议使用
<=> :既可以判断NULL值,又可以判断普通的数值,可读性较低
select 查询列表
from 表名
【where 筛选条件】
order by 排序的字段或表达式;
1、按单个字段排序
SELECT * FROM employees ORDER BY salary DESC;
2、添加筛选条件再排序
案例1:查询部门编号>=90的员工信息,并按员工编号降序
- SELECT *
- FROM employees
- WHERE department_id>=90
- ORDER BY employee_id DESC;
案例2:选择工资不在8000到17000的员工的姓名和工资,按工资降序
- SELECT last_name,salary
- FROM employees
- WHERE salary NOT BETWEEN 8000 AND 17000
- ORDER BY salary DESC;
案例3:查询邮箱中包含e的员工信息,并先按邮箱的字节数降序,再按部门号升序
- SELECT *,LENGTH(email)
- FROM employees
- WHERE email LIKE '%e%'
- ORDER BY LENGTH(email) DESC,department_id ASC;
3、按表达式排序
案例:查询员工信息 按年薪降序
- SELECT *,salary*12*(1+IFNULL(commission_pct,0))
- FROM employees
- ORDER BY salary*12*(1+IFNULL(commission_pct,0)) DESC;
4、按别名排序
案例:查询员工信息 按年薪升序
- SELECT *,salary*12*(1+IFNULL(commission_pct,0)) 年薪
- FROM employees
- ORDER BY 年薪 ASC;
5、按函数排序
案例:查询员工名,并且按名字的长度降序
- SELECT LENGTH(last_name),last_name
- FROM employees
- ORDER BY LENGTH(last_name) DESC;
6、按多个字段排序
案例:查询员工信息,要求先按工资降序,再按employee_id升序
- SELECT *
- FROM employees
- ORDER BY salary DESC,employee_id ASC;
select 查询列表
from 表
【where 筛选条件】
group by 分组的字段
【order by 排序的字段】;
1、和分组函数一同查询的字段必须是group by后出现的字段
2、筛选分为两类:分组前筛选和分组后筛选
分组筛选 | 针对的表 | 位置 | 连接的关键字 |
分组前筛选 | 原始表 | group by前 | where |
分组后筛选 | group by后的结果集 | group by后 | having |
问题1:分组函数做筛选能不能放在where后面
答:不能
问题2:where——group by——having
一般来讲,能用分组前筛选的,尽量使用分组前筛选,提高效率
3、分组可以按单个字段也可以按多个字段
4、可以搭配着排序使用
5、having后可以支持别名
注:用到分组函数的见8.6节
引入:查询某个部门的员工个数
SELECT COUNT(*) FROM employees WHERE department_id=90;
1、简单的分组
案例1:查询每个工种的员工平均工资
- SELECT AVG(salary),job_id
- FROM employees
- GROUP BY job_id;
案例2:查询每个位置的部门个数
- SELECT COUNT(*),location_id
- FROM departments
- GROUP BY location_id;
2、可以实现分组前的筛选
案例1:查询邮箱中包含a字符的 每个部门的最高工资
- SELECT MAX(salary),department_id
- FROM employees
- WHERE email LIKE '%a%'
- GROUP BY department_id;
案例2:查询有奖金的每个领导手下员工的平均工资
- SELECT AVG(salary),manager_id
- FROM employees
- WHERE commission_pct IS NOT NULL
- GROUP BY manager_id;
3、分组后筛选
案例1:查询哪个部门的员工个数>5
①查询每个部门的员工个数
- SELECT COUNT(*),department_id
- FROM employees
- GROUP BY department_id;
② 筛选刚才①结果(使用HAVING)
- SELECT COUNT(*),department_id
- FROM employees
-
- GROUP BY department_id
-
- HAVING COUNT(*)>5;
案例2:每个工种有奖金的员工的最高工资>12000的工种编号和最高工资
- SELECT job_id,MAX(salary)
- FROM employees
- WHERE commission_pct IS NOT NULL
- GROUP BY job_id
- HAVING MAX(salary)>12000;
案例3:领导编号>102的每个领导手下的最低工资大于5000的领导编号和最低工资
- --manager_id>102
-
- SELECT manager_id,MIN(salary)
- FROM employees
- GROUP BY manager_id
- HAVING MIN(salary)>5000;
4.添加排序
案例:每个工种有奖金的员工的最高工资>6000的工种编号和最高工资,按最高工资升序
- SELECT job_id,MAX(salary) m
- FROM employees
- WHERE commission_pct IS NOT NULL
- GROUP BY job_id
- HAVING m>6000
- ORDER BY m ;
5.按多个字段分组
案例:查询每个工种每个部门的最低工资,并按最低工资降序
- SELECT MIN(salary),job_id,department_id
- FROM employees
- GROUP BY department_id,job_id
- ORDER BY MIN(salary) DESC;
6.额外练习
- #1.查询各job_id的员工工资的最大值,最小值,平均值,总和,并按job_id升序
- SELECT MAX(salary),MIN(salary),AVG(salary),SUM(salary),job_id
- FROM employees
- GROUP BY job_id
- ORDER BY job_id;
-
- #2.查询员工最高工资和最低工资的差距(DIFFERENCE)
- SELECT MAX(salary)-MIN(salary) DIFFRENCE
- FROM employees;
-
- #3.查询各个管理者手下员工的最低工资,其中最低工资不能低于6000,没有管理者的员工不计算在内
- SELECT MIN(salary),manager_id
- FROM employees
- WHERE manager_id IS NOT NULL
- GROUP BY manager_id
- HAVING MIN(salary)>=6000;
-
- #4.查询所有部门的编号,员工数量和工资平均值,并按平均工资降序
- SELECT department_id,COUNT(*),AVG(salary) a
- FROM employees
- GROUP BY department_id
- ORDER BY a DESC;
-
- #5.选择具有各个job_id的员工人数
- SELECT COUNT(*) 个数,job_id
- FROM employees
- GROUP BY job_id;
概念:类似于java的方法,将一组逻辑语句封装在方法体中,对外暴露方法名
好处:1、隐藏了实现细节 2、提高代码的重用性
调用:select 函数名(实参列表) 【from 表】;
特点:
①叫什么(函数名)
②干什么(函数功能)
分类:
1、单行函数
如 concat、length、ifnull等
2、分组函数
功能:做统计使用,又称为统计函数、聚合函数、组函数
字符函数:
concat拼接
substr截取子串
upper转换成大写
lower转换成小写
trim去前后指定的空格和字符
ltrim去左边空格
rtrim去右边空格
replace替换
lpad左填充
rpad右填充
instr返回子串第一次出现的索引
length 获取字节个数
数学函数:
round 四舍五入
rand 随机数
floor向下取整
ceil向上取整
mod取余
truncate截断
日期函数:
now当前系统日期+时间
curdate当前系统日期
curtime当前系统时间
str_to_date 将字符转换成日期
date_format将日期转换成字符
year
month
monthname
day
hour
minute
second
其他函数:
version版本
database当前库
user当前连接用户
流程控制函数
if 处理双分支
case语句 处理多分支
情况1:处理等值判断
情况2:处理条件判断if
一、字符函数
- #1.length 获取参数值的字节个数
- SELECT LENGTH('john');
- SELECT LENGTH('张三丰hahaha');
-
- SHOW VARIABLES LIKE '%char%'
-
- #2.concat 拼接字符串
-
- SELECT CONCAT(last_name,'_',first_name) 姓名 FROM employees;
-
- #3.upper、lower
- SELECT UPPER('john');
- SELECT LOWER('joHn');
- #示例:将姓变大写,名变小写,然后拼接
- SELECT CONCAT(UPPER(last_name),LOWER(first_name)) 姓名 FROM employees;
-
- #4.substr、substring
- 注意:索引从1开始
- #截取从指定索引处后面所有字符
- SELECT SUBSTR('李莫愁爱上了陆展元',7) out_put;
-
- #截取从指定索引处指定字符长度的字符
- SELECT SUBSTR('李莫愁爱上了陆展元',1,3) out_put;
-
- #案例:姓名中首字符大写,其他字符小写然后用_拼接,显示出来
-
- SELECT CONCAT(UPPER(SUBSTR(last_name,1,1)),'_',LOWER(SUBSTR(last_name,2))) out_put
- FROM employees;
-
- #5.instr 返回子串第一次出现的索引,如果找不到返回0
-
- SELECT INSTR('杨不殷六侠悔爱上了殷六侠','殷八侠') AS out_put;
-
- #6.trim
-
- SELECT LENGTH(TRIM(' 张翠山 ')) AS out_put;
-
- SELECT TRIM('aa' FROM 'aaaaaaaaa张aaaaaaaaaaaa翠山aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') AS out_put;
-
- #7.lpad 用指定的字符实现左填充指定长度
-
- SELECT LPAD('殷素素',2,'*') AS out_put;
-
- #8.rpad 用指定的字符实现右填充指定长度
-
- SELECT RPAD('殷素素',12,'ab') AS out_put;
-
- #9.replace 替换
-
- SELECT REPLACE('周芷若周芷若周芷若周芷若张无忌爱上了周芷若','周芷若','赵敏') AS out_put;
二、数学函数
- #round 四舍五入
- SELECT ROUND(-1.55);
- SELECT ROUND(1.567,2);
-
- #ceil 向上取整,返回>=该参数的最小整数
-
- SELECT CEIL(-1.02);
-
- #floor 向下取整,返回<=该参数的最大整数
- SELECT FLOOR(-9.99);
-
- #truncate 截断
-
- SELECT TRUNCATE(1.69999,1);
-
- #mod取余
- /*
- mod(a,b) : a-a/b*b
- mod(-10,-3):-10- (-10)/(-3)*(-3)=-1
- */
- SELECT MOD(10,-3);
- SELECT 10%3;
三、日期函数
- #now 返回当前系统日期+时间
- SELECT NOW();
-
- #curdate 返回当前系统日期,不包含时间
- SELECT CURDATE();
-
- #curtime 返回当前时间,不包含日期
- SELECT CURTIME();
-
- #可以获取指定的部分,年、月、日、小时、分钟、秒
- SELECT YEAR(NOW()) 年;
- SELECT YEAR('1998-1-1') 年;
-
- SELECT YEAR(hiredate) 年 FROM employees;
-
- SELECT MONTH(NOW()) 月;
- SELECT MONTHNAME(NOW()) 月;
-
- #str_to_date 将字符通过指定的格式转换成日期
-
- SELECT STR_TO_DATE('1998-3-2','%Y-%c-%d') AS out_put;
-
- #查询入职日期为1992--4-3的员工信息
- SELECT * FROM employees WHERE hiredate = '1992-4-3';
-
- SELECT * FROM employees WHERE hiredate = STR_TO_DATE('4-3 1992','%c-%d %Y');
-
- #date_format 将日期转换成字符
-
- SELECT DATE_FORMAT(NOW(),'%y年%m月%d日') AS out_put;
-
- #查询有奖金的员工名和入职日期(xx月/xx日 xx年)
- SELECT last_name,DATE_FORMAT(hiredate,'%m月/%d日 %y年') 入职日期
- FROM employees
- WHERE commission_pct IS NOT NULL;
四、其他函数
- SELECT VERSION();
- SELECT DATABASE();
- SELECT USER();
五、流程控制函数
1.if函数: if else 的效果
- SELECT IF(10>5,'大','小');
-
- SELECT last_name,commission_pct,IF(commission_pct IS NULL,'没奖金,呵呵','有奖金,嘻嘻') 备注
- FROM employees;
2.case函数的使用一: switch case 的效果
java中
switch(变量或表达式){
case 常量1:语句1;break;
...
default:语句n;break;
}
mysql中
case 要判断的字段或表达式
when 常量1 then 要显示的值1或语句1;
when 常量2 then 要显示的值2或语句2;
...
else 要显示的值n或语句n;
end
案例:查询员工的工资,要求
部门号=30,显示的工资为1.1倍
部门号=40,显示的工资为1.2倍
部门号=50,显示的工资为1.3倍
其他部门,显示的工资为原工资
- SELECT salary 原始工资,department_id,
- CASE department_id
- WHEN 30 THEN salary*1.1
- WHEN 40 THEN salary*1.2
- WHEN 50 THEN salary*1.3
- ELSE salary
- END AS 新工资
- FROM employees;
3.case 函数的使用二:类似于 多重if
java中:
if(条件1){
语句1;
}else if(条件2){
语句2;
}
...
else{
语句n;
}
mysql中:
case
when 条件1 then 要显示的值1或语句1
when 条件2 then 要显示的值2或语句2
。。。
else 要显示的值n或语句n
end
案例:查询员工的工资的情况
如果工资>20000,显示A级别
如果工资>15000,显示B级别
如果工资>10000,显示C级别
否则,显示D级别
- SELECT salary,
- CASE
- WHEN salary>20000 THEN 'A'
- WHEN salary>15000 THEN 'B'
- WHEN salary>10000 THEN 'C'
- ELSE 'D'
- END AS 工资级别
- FROM employees;
额外练习:
- #1. 显示系统时间(注:日期+时间)
- SELECT NOW();
-
- #2. 查询员工号,姓名,工资,以及工资提高百分之20%后的结果(new salary)
-
- SELECT employee_id,last_name,salary,salary*1.2 "new salary"
- FROM employees;
- #3. 将员工的姓名按首字母排序,并写出姓名的长度(length)
-
- SELECT LENGTH(last_name) 长度,SUBSTR(last_name,1,1) 首字符,last_name
- FROM employees
- ORDER BY 首字符;
-
- #4. 做一个查询,产生下面的结果
- <last_name> earns <salary> monthly but wants <salary*3>
- Dream Salary
- King earns 24000 monthly but wants 72000
-
- SELECT CONCAT(last_name,' earns ',salary,' monthly but wants ',salary*3) AS "Dream Salary"
- FROM employees
- WHERE salary=24000;
-
- #5. 使用case-when,按照下面的条件:
- job grade
- AD_PRES A
- ST_MAN B
- IT_PROG C
- SA_REP D
- ST_CLERK E
- 产生下面的结果
- Last_name Job_id Grade
- king AD_PRES A
-
- SELECT last_name,job_id AS job,
- CASE job_id
- WHEN 'AD_PRES' THEN 'A'
- WHEN 'ST_MAN' THEN 'B'
- WHEN 'IT_PROG' THEN 'C'
- WHEN 'SA_PRE' THEN 'D'
- WHEN 'ST_CLERK' THEN 'E'
- END AS Grade
- FROM employees
- WHERE job_id = 'AD_PRES';
-
用作统计使用,又称为聚合函数或统计函数或组函数
sum 求和、avg 平均值、max 最大值 、min 最小值 、count 计算个数
1、简单 的使用
- SELECT SUM(salary) FROM employees;
- SELECT AVG(salary) FROM employees;
- SELECT MIN(salary) FROM employees;
- SELECT MAX(salary) FROM employees;
- SELECT COUNT(salary) FROM employees;
-
- SELECT SUM(salary) 和,AVG(salary) 平均,MAX(salary) 最高,MIN(salary) 最低,COUNT(salary) 个数
- FROM employees;
-
- SELECT SUM(salary) 和,ROUND(AVG(salary),2) 平均,MAX(salary) 最高,MIN(salary) 最低,COUNT(salary) 个数
- FROM employees;
2、参数支持哪些类型
- SELECT SUM(last_name) ,AVG(last_name) FROM employees;
- SELECT SUM(hiredate) ,AVG(hiredate) FROM employees;
-
- SELECT MAX(last_name),MIN(last_name) FROM employees;
- SELECT MAX(hiredate),MIN(hiredate) FROM employees;
-
- SELECT COUNT(commission_pct) FROM employees;
- SELECT COUNT(last_name) FROM employees;
3、是否忽略null
- SELECT SUM(commission_pct) ,AVG(commission_pct),SUM(commission_pct)/35,SUM(commission_pct)/107 FROM employees;
-
- SELECT MAX(commission_pct) ,MIN(commission_pct) FROM employees;
-
- SELECT COUNT(commission_pct) FROM employees;
- SELECT commission_pct FROM employees;
4、和distinct搭配
- SELECT SUM(DISTINCT salary),SUM(salary) FROM employees;
-
- SELECT COUNT(DISTINCT salary),COUNT(salary) FROM employees;
5、count函数的详细介绍
- SELECT COUNT(salary) FROM employees;
-
- SELECT COUNT(*) FROM employees;
-
- SELECT COUNT(1) FROM employees;
效率:
MYISAM存储引擎下 ,COUNT(*)的效率高
INNODB存储引擎下,COUNT(*)和COUNT(1)的效率差不多,比COUNT(字段)要高一些
6、和分组函数一同查询的字段有限制
SELECT AVG(salary),employee_id FROM employees;
额外练习:
- #1.查询公司员工工资的最大值,最小值,平均值,总和
-
- SELECT MAX(salary) 最大值,MIN(salary) 最小值,AVG(salary) 平均值,SUM(salary) 和
- FROM employees;
-
- #2.查询员工表中的最大入职时间和最小入职时间的相差天数 (DIFFRENCE)
-
- SELECT MAX(hiredate) 最大,MIN(hiredate) 最小,(MAX(hiredate)-MIN(hiredate))/1000/3600/24 DIFFRENCE
- FROM employees;
-
- SELECT DATEDIFF(MAX(hiredate),MIN(hiredate)) DIFFRENCE
- FROM employees;
-
- SELECT DATEDIFF('1995-2-7','1995-2-6');
-
- #3.查询部门编号为90的员工个数
-
- SELECT COUNT(*) FROM employees WHERE department_id = 90;
含义:又称多表查询,当查询的字段来自于多个表时,就会用到连接查询
笛卡尔乘积现象:表1 有m行,表2有n行,结果=m*n行
发生原因:没有有效的连接条件
如何避免:添加有效的连接条件
分类:
按年代分类:
sql92标准:仅仅支持内连接
sql99标准【推荐】:支持内连接+外连接(左外和右外)+交叉连接
sql99语法:通过join关键字实现连接;含义:1999年推出的sql语法
按功能分类:
内连接:
等值连接
非等值连接
自连接
外连接:
左外连接
右外连接
全外连接
交叉连接
1)等值连接
① 多表等值连接的结果为多表的交集部分
②n表连接,至少需要n-1个连接条件
③ 多表的顺序没有要求
④一般需要为表起别名
⑤可以搭配前面介绍的所有子句使用,比如排序、分组、筛选
1、基本案例
案例1:查询女神名和对应的男神名
- SELECT * FROM beauty;
-
- SELECT * FROM boys;
-
- SELECT NAME,boyName FROM boys,beauty
- WHERE beauty.boyfriend_id= boys.id;
案例2:查询员工名和对应的部门名
- SELECT last_name,department_name
- FROM employees,departments
- WHERE employees.`department_id`=departments.`department_id`;
2、为表起别名
①提高语句的简洁度
②区分多个重名的字段
注意:如果为表起了别名,则查询的字段就不能使用原来的表名去限定
#查询员工名、工种号、工种名
- SELECT e.last_name,e.job_id,j.job_title
- FROM employees e,jobs j
- WHERE e.`job_id`=j.`job_id`;
3、两个表的顺序是否可以调换
#查询员工名、工种号、工种名
- SELECT e.last_name,e.job_id,j.job_title
- FROM jobs j,employees e
- WHERE e.`job_id`=j.`job_id`;
4、可以加筛选
案例1:查询有奖金的员工名、部门名
- SELECT last_name,department_name,commission_pct
- FROM employees e,departments d
- WHERE e.`department_id`=d.`department_id`
- AND e.`commission_pct` IS NOT NULL;
案例2:查询城市名中第二个字符为o的部门名和城市名
- SELECT department_name,city
- FROM departments d,locations l
- WHERE d.`location_id` = l.`location_id`
- AND city LIKE '_o%';
5、可以加分组
案例1:查询每个城市的部门个数
- SELECT COUNT(*) 个数,city
- FROM departments d,locations l
- WHERE d.`location_id`=l.`location_id`
- GROUP BY city;
案例2:查询有奖金的每个部门的部门名和部门的领导编号和该部门的最低工资
- SELECT department_name,d.`manager_id`,MIN(salary)
- FROM departments d,employees e
- WHERE d.`department_id`=e.`department_id`
- AND commission_pct IS NOT NULL
- GROUP BY department_name,d.`manager_id`;
6、可以加排序
#案例:查询每个工种的工种名和员工的个数,并且按员工个数降序
- SELECT job_title,COUNT(*)
- FROM employees e,jobs j
- WHERE e.`job_id`=j.`job_id`
- GROUP BY job_title
- ORDER BY COUNT(*) DESC;
7、可以实现三表连接?
#案例:查询员工名、部门名和所在的城市
- SELECT last_name,department_name,city
- FROM employees e,departments d,locations l
- WHERE e.`department_id`=d.`department_id`
- AND d.`location_id`=l.`location_id`
- AND city LIKE 's%'
-
- ORDER BY department_name DESC;
2)非等值连接
案例1:查询员工的工资和工资级别
- SELECT salary,grade_level
- FROM employees e,job_grades g
- WHERE salary BETWEEN g.`lowest_sal` AND g.`highest_sal`
- AND g.`grade_level`='A';
- select salary,employee_id from employees;
- select * from job_grades;
创建工资等级表:
- CREATE TABLE job_grades
- (grade_level VARCHAR(3),
- lowest_sal int,
- highest_sal int);
-
- INSERT INTO job_grades
- VALUES ('A', 1000, 2999);
-
- INSERT INTO job_grades
- VALUES ('B', 3000, 5999);
-
- INSERT INTO job_grades
- VALUES('C', 6000, 9999);
-
- INSERT INTO job_grades
- VALUES('D', 10000, 14999);
-
- INSERT INTO job_grades
- VALUES('E', 15000, 24999);
-
- INSERT INTO job_grades
- VALUES('F', 25000, 40000);
3)自连接
案例:查询 员工名和上级的名称
- SELECT e.employee_id,e.last_name,m.employee_id,m.last_name
- FROM employees e,employees m
- WHERE e.`manager_id`=m.`employee_id`;
语法:
select 字段,...
from 表1
【inner|left outer|right outer|cross】join 表2 on 连接条件
【inner|left outer|right outer|cross】join 表3 on 连接条件
【where 筛选条件】
【group by 分组字段】
【having 分组后的筛选条件】
【order by 排序的字段或表达式】
好处:语句上,连接条件和筛选条件实现了分离,简洁明了!
分类:
内连接(★):inner
外连接
左外(★):left 【outer】
右外(★):right 【outer】
全外:full【outer】
交叉连接:cross
Ⅰ、内连接
语法:
select 查询列表
from 表1 别名
inner join 表2 别名
on 连接条件;
分类:
等值
非等值
自连接
特点:
①添加排序、分组、筛选
②inner可以省略
③ 筛选条件放在where后面,连接条件放在on后面,提高分离性,便于阅读
④inner join连接和sql92语法中的等值连接效果是一样的,都是查询多表的交集
1)等值连接
案例1.查询员工名、部门名
- SELECT last_name,department_name
- FROM departments d
- JOIN employees e
- ON e.`department_id` = d.`department_id`;
案例2.查询名字中包含e的员工名和工种名(添加筛选)
- SELECT last_name,job_title
- FROM employees e
- INNER JOIN jobs j
- ON e.`job_id`= j.`job_id`
- WHERE e.`last_name` LIKE '%e%';
案例3. 查询部门个数>3的城市名和部门个数,(添加分组+筛选)
#①查询每个城市的部门个数
#②在①结果上筛选满足条件的
- SELECT city,COUNT(*) 部门个数
- FROM departments d
- INNER JOIN locations l
- ON d.`location_id`=l.`location_id`
- GROUP BY city
- HAVING COUNT(*)>3;
案例4.查询哪个部门的员工个数>3的部门名和员工个数,并按个数降序(添加排序)
#①查询每个部门的员工个数
- SELECT COUNT(*),department_name
- FROM employees e
- INNER JOIN departments d
- ON e.`department_id`=d.`department_id`
- GROUP BY department_name
#② 在①结果上筛选员工个数>3的记录,并排序
- SELECT COUNT(*) 个数,department_name
- FROM employees e
- INNER JOIN departments d
- ON e.`department_id`=d.`department_id`
- GROUP BY department_name
- HAVING COUNT(*)>3
- ORDER BY COUNT(*) DESC;
案例5.查询员工名、部门名、工种名,并按部门名降序(添加三表连接)
- SELECT last_name,department_name,job_title
- FROM employees e
- INNER JOIN departments d ON e.`department_id`=d.`department_id`
- INNER JOIN jobs j ON e.`job_id` = j.`job_id`
-
- ORDER BY department_name DESC;
2)非等值连接
#查询员工的工资级别
- SELECT salary,grade_level
- FROM employees e
- JOIN job_grades g
- ON e.`salary` BETWEEN g.`lowest_sal` AND g.`highest_sal`;
#查询工资级别的个数>20的个数,并且按工资级别降序
- SELECT COUNT(*),grade_level
- FROM employees e
- JOIN job_grades g
- ON e.`salary` BETWEEN g.`lowest_sal` AND g.`highest_sal`
- GROUP BY grade_level
- HAVING COUNT(*)>20
- ORDER BY grade_level DESC;
3)自连接
#查询员工的名字、上级的名字
- SELECT e.last_name,m.last_name
- FROM employees e
- JOIN employees m
- ON e.`manager_id`= m.`employee_id`;
#查询姓名中包含字符k的员工的名字、上级的名字
- SELECT e.last_name,m.last_name
- FROM employees e
- JOIN employees m
- ON e.`manager_id`= m.`employee_id`
- WHERE e.`last_name` LIKE '%k%';
Ⅱ、外连接
应用场景:用于查询一个表中有,另一个表没有的记录
特点:
1、外连接的查询结果为主表中的所有记录
如果从表中有和它匹配的,则显示匹配的值
如果从表中没有和它匹配的,则显示null
外连接查询结果=内连接结果+主表中有而从表没有的记录
2、左外连接,left join左边的是主表
右外连接,right join右边的是主表
3、左外和右外交换两个表的顺序,可以实现同样的效果
4、全外连接=内连接的结果+表1中有但表2没有的+表2中有但表1没有的
#引入:查询男朋友不在男神表的的女神名
- SELECT * FROM beauty;
- SELECT * FROM boys;
#左外连接
- SELECT b.*,bo.*
- FROM boys bo
- LEFT OUTER JOIN beauty b
- ON b.`boyfriend_id` = bo.`id`
- WHERE b.`id` IS NULL;
#案例1:查询哪个部门没有员工
左外
- SELECT d.*,e.employee_id
- FROM departments d
- LEFT OUTER JOIN employees e
- ON d.`department_id` = e.`department_id`
- WHERE e.`employee_id` IS NULL;
右外
- SELECT d.*,e.employee_id
- FROM employees e
- RIGHT OUTER JOIN departments d
- ON d.`department_id` = e.`department_id`
- WHERE e.`employee_id` IS NULL;
全外
- USE girls;
- SELECT b.*,bo.*
- FROM beauty b
- FULL OUTER JOIN boys bo
- ON b.`boyfriend_id` = bo.id;
Ⅲ、交叉连接
- SELECT b.*,bo.*
- FROM beauty b
- CROSS JOIN boys bo;
sql92 VS sql99
功能:sql99支持的较多
可读性:sql99实现连接条件和筛选条件的分离,可读性较高
自连接:
案例:查询员工名和直接上级的名称
- sql99
- SELECT e.last_name,m.last_name
- FROM employees e
- JOIN employees m ON e.`manager_id`=m.`employee_id`;
-
- sql92
- SELECT e.last_name,m.last_name
- FROM employees e,employees m
- WHERE e.`manager_id`=m.`employee_id`;
外连接:
- #一、查询编号>3的女神的男朋友信息,如果有则列出详细,如果没有,用null填充
-
- SELECT b.id,b.name,bo.*
- FROM beauty b
- LEFT OUTER JOIN boys bo
- ON b.`boyfriend_id` = bo.`id`
- WHERE b.`id`>3;
- #二、查询哪个城市没有部门
-
- SELECT city
- FROM departments d
- RIGHT OUTER JOIN locations l
- ON d.`location_id`=l.`location_id`
- WHERE d.`department_id` IS NULL;
-
- #三、查询部门名为SAL或IT的员工信息
-
- SELECT e.*,d.department_name,d.`department_id`
- FROM departments d
- LEFT JOIN employees e
- ON d.`department_id` = e.`department_id`
- WHERE d.`department_name` IN('SAL','IT');
-
-
- SELECT * FROM departments
- WHERE `department_name` IN('SAL','IT');
额外练习:
- #1.显示所有员工的姓名,部门号和部门名称。
- USE myemployees;
-
- SELECT last_name,d.department_id,department_name
- FROM employees e,departments d
- WHERE e.`department_id` = d.`department_id`;
-
- #2.查询90号部门员工的job_id和90号部门的location_id
-
- SELECT job_id,location_id
- FROM employees e,departments d
- WHERE e.`department_id`=d.`department_id`
- AND e.`department_id`=90;
-
- #3. 选择所有有奖金的员工的
- last_name , department_name , location_id , city
-
- SELECT last_name , department_name , l.location_id , city
- FROM employees e,departments d,locations l
- WHERE e.department_id = d.department_id
- AND d.location_id=l.location_id
- AND e.commission_pct IS NOT NULL;
-
- #4.选择city在Toronto工作的员工的
- last_name , job_id , department_id , department_name
-
- SELECT last_name , job_id , d.department_id , department_name
- FROM employees e,departments d ,locations l
- WHERE e.department_id = d.department_id
- AND d.location_id=l.location_id
- AND city = 'Toronto';
-
- #5.查询每个工种、每个部门的部门名、工种名和最低工资
-
- SELECT department_name,job_title,MIN(salary) 最低工资
- FROM employees e,departments d,jobs j
- WHERE e.`department_id`=d.`department_id`
- AND e.`job_id`=j.`job_id`
- GROUP BY department_name,job_title;
-
- #6.查询每个国家下的部门个数大于2的国家编号
-
- SELECT country_id,COUNT(*) 部门个数
- FROM departments d,locations l
- WHERE d.`location_id`=l.`location_id`
- GROUP BY country_id
- HAVING 部门个数>2;
-
- #7、选择指定员工的姓名,员工号,以及他的管理者的姓名和员工号,结果类似于下面的格式
- employees Emp# manager Mgr#
- kochhar 101 king 100
-
- SELECT e.last_name employees,e.employee_id "Emp#",m.last_name manager,m.employee_id "Mgr#"
- FROM employees e,employees m
- WHERE e.manager_id = m.employee_id
- AND e.last_name='kochhar';
含义:
出现在其他语句中的select语句,称为子查询或内查询
外部的查询语句,称为主查询或外查询
分类:
按子查询出现的位置:
select后面:
仅仅支持标量子查询
from后面:
支持表子查询
where或having后面:★
标量子查询(单行) √
列子查询 (多行) √
行子查询
exists后面(相关子查询)
表子查询
按结果集的行列数不同:
Ⅰ、where或having后面
特点:
①子查询放在小括号内
②子查询一般放在条件的右侧
③标量子查询,一般搭配着单行操作符使用
> < >= <= = <>
列子查询,一般搭配着多行操作符使用
in、any/some、all
④子查询的执行优先于主查询执行,主查询的条件用到了子查询的结果
1.标量子查询★
案例1:谁的工资比 Abel 高?
①查询Abel的工资
- SELECT salary
- FROM employees
- WHERE last_name = 'Abel'
查询员工的信息,满足 salary>①结果
- SELECT *
- FROM employees
- WHERE salary>(
-
- SELECT salary
- FROM employees
- WHERE last_name = 'Abel'
- );
案例2:返回job_id与141号员工相同,salary比143号员工多的员工姓名,job_id 和工资
①查询141号员工的job_id
- SELECT job_id
- FROM employees
- WHERE employee_id = 141
②查询143号员工的salary
- SELECT salary
- FROM employees
- WHERE employee_id = 143
③查询员工的姓名,job_id 和工资,要求job_id=①并且salary>②
- SELECT last_name,job_id,salary
- FROM employees
- WHERE job_id = (
- SELECT job_id
- FROM employees
- WHERE employee_id = 141
- ) AND salary>(
- SELECT salary
- FROM employees
- WHERE employee_id = 143
-
- );
案例3:返回公司工资最少的员工的last_name,job_id和salary
①查询公司的 最低工资
- SELECT MIN(salary)
- FROM employees
②查询last_name,job_id和salary,要求salary=①
- SELECT last_name,job_id,salary
- FROM employees
- WHERE salary=(
- SELECT MIN(salary)
- FROM employees
- );
案例4:查询最低工资大于50号部门最低工资的部门id和其最低工资
①查询50号部门的最低工资
- SELECT MIN(salary)
- FROM employees
- WHERE department_id = 50
②查询每个部门的最低工资
- SELECT MIN(salary),department_id
- FROM employees
- GROUP BY department_id
③ 在②基础上筛选,满足min(salary)>①
- SELECT MIN(salary),department_id
- FROM employees
- GROUP BY department_id
- HAVING MIN(salary)>(
- SELECT MIN(salary)
- FROM employees
- WHERE department_id = 50
- );
非法使用标量子查询
- SELECT MIN(salary),department_id
- FROM employees
- GROUP BY department_id
- HAVING MIN(salary)>(
- SELECT salary
- FROM employees
- WHERE department_id = 250
- );
2.列子查询(多行子查询)★
案例1:返回location_id是1400或1700的部门中的所有员工姓名
①查询location_id是1400或1700的部门编号
- SELECT DISTINCT department_id
- FROM departments
- WHERE location_id IN(1400,1700)
②查询员工姓名,要求部门号是①列表中的某一个
- SELECT last_name
- FROM employees
- WHERE department_id <>ALL(
- SELECT DISTINCT department_id
- FROM departments
- WHERE location_id IN(1400,1700)
- );
案例2:返回其它工种中比job_id为‘IT_PROG’工种任一工资低的员工的员工号、姓名、job_id 以及salary
①查询job_id为‘IT_PROG’部门任一工资
- SELECT DISTINCT salary
- FROM employees
- WHERE job_id = 'IT_PROG';
②查询员工号、姓名、job_id 以及salary,salary<(①)的任意一个
- SELECT last_name,employee_id,job_id,salary
- FROM employees
- WHERE salary<ANY(
- SELECT DISTINCT salary
- FROM employees
- WHERE job_id = 'IT_PROG'
-
- ) AND job_id<>'IT_PROG';
或
- SELECT last_name,employee_id,job_id,salary
- FROM employees
- WHERE salary<(
- SELECT MAX(salary)
- FROM employees
- WHERE job_id = 'IT_PROG'
-
- ) AND job_id<>'IT_PROG';
案例3:返回其它部门中比job_id为‘IT_PROG’部门所有工资都低的员工 的员工号、姓名、job_id 以及salary
- SELECT last_name,employee_id,job_id,salary
- FROM employees
- WHERE salary<ALL(
- SELECT DISTINCT salary
- FROM employees
- WHERE job_id = 'IT_PROG'
-
- ) AND job_id<>'IT_PROG';
或
- SELECT last_name,employee_id,job_id,salary
- FROM employees
- WHERE salary<(
- SELECT MIN( salary)
- FROM employees
- WHERE job_id = 'IT_PROG'
-
- ) AND job_id<>'IT_PROG';
3、行子查询(结果集一行多列或多行多列)
案例:查询员工编号最小并且工资最高的员工信息
- SELECT *
- FROM employees
- WHERE (employee_id,salary)=(
- SELECT MIN(employee_id),MAX(salary)
- FROM employees
- );
①查询最小的员工编号
- SELECT MIN(employee_id)
- FROM employees
②查询最高工资
- SELECT MAX(salary)
- FROM employees
③查询员工信息
- SELECT *
- FROM employees
- WHERE employee_id=(
- SELECT MIN(employee_id)
- FROM employees
-
- )AND salary=(
- SELECT MAX(salary)
- FROM employees
-
- );
Ⅱ、select后面
仅仅支持标量子查询
案例:查询每个部门的员工个数
- SELECT d.*,(
-
- SELECT COUNT(*)
- FROM employees e
- WHERE e.department_id = d.`department_id`
- ) 个数
- FROM departments d;
案例2:查询员工号=102的部门名
- SELECT (
- SELECT department_name,e.department_id
- FROM departments d
- INNER JOIN employees e
- ON d.department_id=e.department_id
- WHERE e.employee_id=102
-
- ) 部门名;
Ⅲ、from后面
将子查询结果充当一张表,要求必须起别名
案例:查询每个部门的平均工资的工资等级
①查询每个部门的平均工资
- SELECT AVG(salary),department_id
- FROM employees
- GROUP BY department_id
-
-
- SELECT * FROM job_grades;
②连接①的结果集和job_grades表,筛选条件平均工资 between lowest_sal and highest_sal
- SELECT ag_dep.*,g.`grade_level`
- FROM (
- SELECT AVG(salary) ag,department_id
- FROM employees
- GROUP BY department_id
- ) ag_dep
- INNER JOIN job_grades g
- ON ag_dep.ag BETWEEN lowest_sal AND highest_sal;
Ⅳ、exists后面(相关子查询)
语法:
exists(完整的查询语句)
结果:
1或0
SELECT EXISTS(SELECT employee_id FROM employees WHERE salary=300000);
案例1:查询有员工的部门名
in
- SELECT department_name
- FROM departments d
- WHERE d.`department_id` IN(
- SELECT department_id
- FROM employees
- );
#exists
- SELECT department_name
- FROM departments d
- WHERE EXISTS(
- SELECT *
- FROM employees e
- WHERE d.`department_id`=e.`department_id`
- );
案例2:查询没有女朋友的男神信息
in
- SELECT bo.*
- FROM boys bo
- WHERE bo.id NOT IN(
- SELECT boyfriend_id
- FROM beauty
- )
exists
- SELECT bo.*
- FROM boys bo
- WHERE NOT EXISTS(
- SELECT boyfriend_id
- FROM beauty b
- WHERE bo.`id`=b.`boyfriend_id`
-
- );
额外练习:
- #1. 查询和Zlotkey相同部门的员工姓名和工资
-
- #①查询Zlotkey的部门
- SELECT department_id
- FROM employees
- WHERE last_name = 'Zlotkey'
-
- #②查询部门号=①的姓名和工资
- SELECT last_name,salary
- FROM employees
- WHERE department_id = (
- SELECT department_id
- FROM employees
- WHERE last_name = 'Zlotkey'
- )
-
- #2.查询工资比公司平均工资高的员工的员工号,姓名和工资。
-
- #①查询平均工资
- SELECT AVG(salary)
- FROM employees
-
- #②查询工资>①的员工号,姓名和工资。
-
- SELECT last_name,employee_id,salary
- FROM employees
- WHERE salary>(
- SELECT AVG(salary)
- FROM employees
- );
-
- #3.查询各部门中工资比本部门平均工资高的员工的员工号, 姓名和工资
- #①查询各部门的平均工资
- SELECT AVG(salary),department_id
- FROM employees
- GROUP BY department_id
-
- #②连接①结果集和employees表,进行筛选
- SELECT employee_id,last_name,salary,e.department_id
- FROM employees e
- INNER JOIN (
- SELECT AVG(salary) ag,department_id
- FROM employees
- GROUP BY department_id
- ) ag_dep
- ON e.department_id = ag_dep.department_id
- WHERE salary>ag_dep.ag ;
-
- #4. 查询和姓名中包含字母u的员工在相同部门的员工的员工号和姓名
- #①查询姓名中包含字母u的员工的部门
-
- SELECT DISTINCT department_id
- FROM employees
- WHERE last_name LIKE '%u%'
-
- #②查询部门号=①中的任意一个的员工号和姓名
- SELECT last_name,employee_id
- FROM employees
- WHERE department_id IN(
- SELECT DISTINCT department_id
- FROM employees
- WHERE last_name LIKE '%u%'
- );
-
-
- #5. 查询在部门的location_id为1700的部门工作的员工的员工号
-
- #①查询location_id为1700的部门
-
- SELECT DISTINCT department_id
- FROM departments
- WHERE location_id = 1700
-
- #②查询部门号=①中的任意一个的员工号
- SELECT employee_id
- FROM employees
- WHERE department_id =ANY(
- SELECT DISTINCT department_id
- FROM departments
- WHERE location_id = 1700
-
- );
- #6.查询管理者是King的员工姓名和工资
-
- #①查询姓名为king的员工编号
- SELECT employee_id
- FROM employees
- WHERE last_name = 'K_ing'
-
- #②查询哪个员工的manager_id = ①
- SELECT last_name,salary
- FROM employees
- WHERE manager_id IN(
- SELECT employee_id
- FROM employees
- WHERE last_name = 'K_ing'
-
- );
-
- #7.查询工资最高的员工的姓名,要求first_name和last_name显示为一列,列名为 姓.名
-
- #①查询最高工资
- SELECT MAX(salary)
- FROM employees
-
- #②查询工资=①的姓.名
-
- SELECT CONCAT(first_name,last_name) "姓.名"
- FROM employees
- WHERE salary=(
- SELECT MAX(salary)
- FROM employees
-
- );
应用场景:当要显示的数据,一页显示不全,需要分页提交sql请求
语法:
select 查询列表
from 表
【join type join 表2
on 连接条件
where 筛选条件
group by 分组字段
having 分组后的筛选
order by 排序的字段】
limit 【offset,】size;
offset要显示条目的起始索引(起始索引从0开始)
size 要显示的条目个数
特点:
①limit语句放在查询语句的最后
②公式
要显示的页数 page,每页的条目数size
select 查询列表
from 表
limit (page-1)*size,size;
size=10
page
1 0
2 10
3 20
#案例1:查询前五条员工信息
- SELECT * FROM employees LIMIT 0,5;
- SELECT * FROM employees LIMIT 5;
#案例2:查询第11条——第25条
SELECT * FROM employees LIMIT 10,15;
#案例3:有奖金的员工信息,并且工资较高的前10名显示出来
- SELECT
- *
- FROM
- employees
- WHERE commission_pct IS NOT NULL
- ORDER BY salary DESC
- LIMIT 10 ;
引入:
union 联合、合并:将多条查询语句的结果合并成一个结果
语法:
select 字段|常量|表达式|函数 【from 表】 【where 条件】 union 【all】
select 字段|常量|表达式|函数 【from 表】 【where 条件】 union 【all】
select 字段|常量|表达式|函数 【from 表】 【where 条件】 union 【all】
.....
select 字段|常量|表达式|函数 【from 表】 【where 条件】
查询语句1
union
查询语句2
union
...
特点:
1、多条查询语句的查询的列数必须是一致的
2、多条查询语句的查询的列的类型几乎相同
3、union代表去重,union all可以包含重复项
案例1:查询部门编号>90或邮箱包含a的员工信息
- SELECT * FROM employees WHERE email LIKE '%a%' OR department_id>90;
-
- SELECT * FROM employees WHERE email LIKE '%a%'
- UNION
- SELECT * FROM employees WHERE department_id>90;
案例2:查询中国用户中男性的信息以及外国用户中年男性的用户信息
- SELECT id,cname FROM t_ca WHERE csex='男'
- UNION ALL
- SELECT t_id,tname FROM t_ua WHERE tGender='male';
方式一:经典的插入
语法:
insert into 表名(列名,...) values(值1,...);
- SELECT * FROM beauty;
- #1.插入的值的类型要与列的类型一致或兼容
- INSERT INTO beauty(id,NAME,sex,borndate,phone,photo,boyfriend_id)
- VALUES(13,'唐艺昕','女','1990-4-23','1898888888',NULL,2);
-
- #2.不可以为null的列必须插入值。可以为null的列如何插入值?
- #方式1:
- INSERT INTO beauty(id,NAME,sex,borndate,phone,photo,boyfriend_id)
- VALUES(13,'唐艺昕','女','1990-4-23','1898888888',NULL,2);
-
- #方式2:
-
- INSERT INTO beauty(id,NAME,sex,phone)
- VALUES(15,'娜扎','女','1388888888');
-
- #3.列的顺序是否可以调换
- INSERT INTO beauty(NAME,sex,id,phone)
- VALUES('蒋欣','女',16,'110');
-
- #4.列数和值的个数必须一致
-
- INSERT INTO beauty(NAME,sex,id,phone)
- VALUES('关晓彤','女',17,'110');
-
- #5.可以省略列名,默认所有列,而且列的顺序和表中列的顺序一致
-
- INSERT INTO beauty
- VALUES(18,'张飞','男',NULL,'119',NULL,NULL);
方式二:
语法:
insert into 表名
set 列名=值,列名=值,...
- INSERT INTO beauty
- SET id=19,NAME='刘涛',phone='999';
两种方式大pk ★
#1、方式一支持插入多行,方式二不支持
INSERT INTO beauty
VALUES(23,'唐艺昕1','女','1990-4-23','1898888888',NULL,2)
,(24,'唐艺昕2','女','1990-4-23','1898888888',NULL,2)
,(25,'唐艺昕3','女','1990-4-23','1898888888',NULL,2);
#2、方式一支持子查询,方式二不支持
INSERT INTO beauty(id,NAME,phone)
SELECT 26,'宋茜','11809866';
INSERT INTO beauty(id,NAME,phone)
SELECT id,boyname,'1234567'
FROM boys WHERE id<3;
1.修改单表的记录★
语法:
update 表名
set 列=新值,列=新值,...
where 筛选条件;
2.修改多表的记录【补充】
语法:
sql92语法:
update 表1 别名,表2 别名
set 列=值,...
where 连接条件
and 筛选条件;
sql99语法:
update 表1 别名
inner|left|right join 表2 别名
on 连接条件
set 列=值,...
where 筛选条件;
#1.修改单表的记录
#案例1:修改beauty表中姓唐的女神的电话为13899888899
UPDATE beauty SET phone = '13899888899'
WHERE NAME LIKE '唐%';
#案例2:修改boys表中id好为2的名称为张飞,魅力值 10
UPDATE boys SET boyname='张飞',usercp=10
WHERE id=2;
#2.修改多表的记录
#案例 1:修改张无忌的女朋友的手机号为114
UPDATE boys bo
INNER JOIN beauty b ON bo.`id`=b.`boyfriend_id`
SET b.`phone`='119',bo.`userCP`=1000
WHERE bo.`boyName`='张无忌';
#案例2:修改没有男朋友的女神的男朋友编号都为2号
UPDATE boys bo
RIGHT JOIN beauty b ON bo.`id`=b.`boyfriend_id`
SET b.`boyfriend_id`=2
WHERE bo.`id` IS NULL;
SELECT * FROM boys
方式一:delete
语法:
1、单表的删除【★】
delete from 表名 where 筛选条件
2、多表的删除【补充】
sql92语法:
delete 表1的别名,表2的别名
from 表1 别名,表2 别名
where 连接条件
and 筛选条件;
sql99语法:
delete 表1的别名,表2的别名
from 表1 别名
inner|left|right join 表2 别名 on 连接条件
where 筛选条件;
方式二:truncate
语法:truncate table 表名;
#方式一:delete
#1.单表的删除
#案例:删除手机号以9结尾的女神信息
DELETE FROM beauty WHERE phone LIKE '%9';
SELECT * FROM beauty;
#2.多表的删除
#案例:删除张无忌的女朋友的信息
DELETE b
FROM beauty b
INNER JOIN boys bo ON b.`boyfriend_id` = bo.`id`
WHERE bo.`boyName`='张无忌';
#案例:删除黄晓明的信息以及他女朋友的信息
DELETE b,bo
FROM beauty b
INNER JOIN boys bo ON b.`boyfriend_id`=bo.`id`
WHERE bo.`boyName`='黄晓明';
#方式二:truncate语句
#案例:将魅力值>100的男神信息删除
TRUNCATE TABLE boys ;
#delete pk truncate【面试题★】
/*
1.delete 可以加where 条件,truncate不能加
2.truncate删除,效率高一丢丢
3.假如要删除的表中有自增长列,
如果用delete删除后,再插入数据,自增长列的值从断点开始,
而truncate删除后,再插入数据,自增长列的值从1开始。
4.truncate删除没有返回值,delete删除有返回值
5.truncate删除不能回滚,delete删除可以回滚.
*/
SELECT * FROM boys;
DELETE FROM boys;
TRUNCATE TABLE boys;
INSERT INTO boys (boyname,usercp)
VALUES('张飞',100),('刘备',100),('关云长',100);
数据的增删改额外练习
- #1. 运行以下脚本创建表my_employees
-
- USE myemployees;
- CREATE TABLE my_employees(
- Id INT(10),
- First_name VARCHAR(10),
- Last_name VARCHAR(10),
- Userid VARCHAR(10),
- Salary DOUBLE(10,2)
- );
- CREATE TABLE users(
- id INT,
- userid VARCHAR(10),
- department_id INT
-
- );
- #2. 显示表my_employees的结构
- DESC my_employees;
-
- #3. 向my_employees表中插入下列数据
- ID FIRST_NAME LAST_NAME USERID SALARY
- 1 patel Ralph Rpatel 895
- 2 Dancs Betty Bdancs 860
- 3 Biri Ben Bbiri 1100
- 4 Newman Chad Cnewman 750
- 5 Ropeburn Audrey Aropebur 1550
-
- #方式一:
- INSERT INTO my_employees
- VALUES(1,'patel','Ralph','Rpatel',895),
- (2,'Dancs','Betty','Bdancs',860),
- (3,'Biri','Ben','Bbiri',1100),
- (4,'Newman','Chad','Cnewman',750),
- (5,'Ropeburn','Audrey','Aropebur',1550);
- DELETE FROM my_employees;
- #方式二:
-
- INSERT INTO my_employees
- SELECT 1,'patel','Ralph','Rpatel',895 UNION
- SELECT 2,'Dancs','Betty','Bdancs',860 UNION
- SELECT 3,'Biri','Ben','Bbiri',1100 UNION
- SELECT 4,'Newman','Chad','Cnewman',750 UNION
- SELECT 5,'Ropeburn','Audrey','Aropebur',1550;
-
-
- #4. 向users表中插入数据
- 1 Rpatel 10
- 2 Bdancs 10
- 3 Bbiri 20
- 4 Cnewman 30
- 5 Aropebur 40
-
- INSERT INTO users
- VALUES(1,'Rpatel',10),
- (2,'Bdancs',10),
- (3,'Bbiri',20);
-
- #5.将3号员工的last_name修改为“drelxer”
- UPDATE my_employees SET last_name='drelxer' WHERE id = 3;
-
- #6.将所有工资少于900的员工的工资修改为1000
- UPDATE my_employees SET salary=1000 WHERE salary<900;
-
- #7.将userid 为Bbiri的user表和my_employees表的记录全部删除
-
- DELETE u,e
- FROM users u
- JOIN my_employees e ON u.`userid`=e.`Userid`
- WHERE u.`userid`='Bbiri';
-
- #8.删除所有数据
-
- DELETE FROM my_employees;
- DELETE FROM users;
- #9.检查所作的修正
-
- SELECT * FROM my_employees;
- SELECT * FROM users;
-
- #10.清空表my_employees
- TRUNCATE TABLE my_employees;
一个或一组sql语句组成一个执行单元,这个执行单元要么全部执行,要么全部不执行。
ACID
原子性:一个事务不可再分割,要么都执行要么都不执行
一致性:一个事务执行会使数据从一个一致状态切换到另外一个一致状态
隔离性:一个事务的执行不受其他事务的干扰
持久性:一个事务一旦提交,则会永久的改变数据库的数据.
隐式事务,没有明显的开启和结束事务的标志
比如
insert、update、delete语句本身就是一个事务
显式事务,具有明显的开启和结束事务的标志
1、开启事务
取消自动提交事务的功能
2、编写事务的一组逻辑操作单元(多条sql语句)
insert
update
delete
3、提交事务或回滚事务
set autocommit=0;
start transaction;
commit;
rollback;
savepoint 断点
commit to 断点
rollback to 断点
事务并发问题如何发生?
当多个事务同时操作同一个数据库的相同数据时
事务的并发问题有哪些?
如何避免事务的并发问题?
通过设置事务的隔离级别
1、READ UNCOMMITTED
2、READ COMMITTED 可以避免脏读
3、REPEATABLE READ 可以避免脏读、不可重复读和一部分幻读
4、SERIALIZABLE可以避免脏读、不可重复读和幻读
设置隔离级别:
set session|global transaction isolation level 隔离级别名;
查看隔离级别:
select @@tx_isolation;
事务的创建
隐式事务:事务没有明显的开启和结束的标记
比如insert、update、delete语句
delete from 表 where id =1;
显式事务:事务具有明显的开启和结束的标记
前提:必须先设置自动提交功能为禁用
set autocommit=0;
步骤1:开启事务
set autocommit=0;
start transaction;可选的
步骤2:编写事务中的sql语句(select insert update delete)
语句1;
语句2;
...
步骤3:结束事务
commit;提交事务
rollback;回滚事务
savepoint 节点名;设置保存点
事务的隔离级别:
脏读 | 不可重复读 | 幻读 | |
read uncommitted | √ | √ | √ |
read committed | × | √ | √ |
repeatable read | × | × | √ |
serializable | × | × | × |
mysql中默认 第三个隔离级别 repeatable read
oracle中默认第二个隔离级别 read committed
查看隔离级别
select @@tx_isolation;
设置隔离级别
set session|global transaction isolation level 隔离级别;
开启事务的语句;
update 表 set 张三丰的余额=500 where name='张三丰'
update 表 set 郭襄的余额=1500 where name='郭襄'
结束事务的语句;
SHOW VARIABLES LIKE 'autocommit';
SHOW ENGINES;
1.演示事务的使用步骤
- #开启事务
- SET autocommit=0;
- START TRANSACTION;
- #编写一组事务的语句
- UPDATE account SET balance = 1000 WHERE username='张无忌';
- UPDATE account SET balance = 1000 WHERE username='赵敏';
-
- #结束事务
- ROLLBACK;
- #commit;
-
- SELECT * FROM account;
2.演示事务对于delete和truncate的处理的区别
- SET autocommit=0;
- START TRANSACTION;
-
- DELETE FROM account;
- ROLLBACK;
3.演示savepoint 的使用
- SET autocommit=0;
- START TRANSACTION;
- DELETE FROM account WHERE id=25;
- SAVEPOINT a;#设置保存点
- DELETE FROM account WHERE id=28;
- ROLLBACK TO a;#回滚到保存点
-
- SELECT * FROM account;
一张虚拟的表(逻辑表),不占用物理空间。
使用方式 | 占用物理空间 | |
视图 | 完全相同 | 不占用,仅仅保存的是sql逻辑 |
表 | 完全相同 | 占用 |
1、sql语句提高重用性,效率高
2、和表实现了分离,提高了安全性
语法:
CREATE VIEW 视图名
AS
查询语句;
1、查看视图的数据 ★
- SELECT * FROM my_v4;
- SELECT * FROM my_v1 WHERE last_name='Partners';
2、插入视图的数据
INSERT INTO my_v4(last_name,department_id) VALUES('虚竹',90);
3、修改视图的数据
UPDATE my_v4 SET last_name ='梦姑' WHERE last_name='虚竹';
4、删除视图的数据
DELETE FROM my_v4;
11.7 视图逻辑的更新
- #方式一:
- CREATE OR REPLACE VIEW test_v7
- AS
- SELECT last_name FROM employees
- WHERE employee_id>100;
-
- #方式二:
- ALTER VIEW test_v7
- AS
- SELECT employee_id FROM employees;
-
- SELECT * FROM test_v7;
11.8 视图的删除
DROP VIEW test_v1,test_v2,test_v3;
11.9 视图结构的查看
- DESC test_v7;
- SHOW CREATE VIEW test_v7;
11.10 案例
案例一:创建视图emp_v1,要求查询电话号码以‘011’开头的员工姓名和工资、邮箱
- CREATE OR REPLACE VIEW emp_v1
- AS
- SELECT last_name,salary,email
- FROM employees
- WHERE phone_number LIKE '011%';
案例二:创建视图emp_v2,要求查询部门的最高工资高于12000的部门信息
- CREATE OR REPLACE VIEW emp_v2
- AS
- SELECT MAX(salary) mx_dep,department_id
- FROM employees
- GROUP BY department_id
- HAVING MAX(salary)>12000;
-
- SELECT d.*,m.mx_dep
- FROM departments d
- JOIN emp_v2 m
- ON m.department_id = d.`department_id`;
系统变量:
全局变量
会话变量
自定义变量:
用户变量
局部变量
#一、系统变量
/*
说明:变量由系统定义,不是用户定义,属于服务器层面
注意:全局变量需要添加global关键字,会话变量需要添加session关键字,如果不写,默认会话级别
使用步骤:
1、查看所有系统变量
show global|【session】variables;
2、查看满足条件的部分系统变量
show global|【session】 variables like '%char%';
3、查看指定的系统变量的值
select @@global|【session】系统变量名;
4、为某个系统变量赋值
方式一:
set global|【session】系统变量名=值;
方式二:
set @@global|【session】系统变量名=值;
*/
#1》全局变量
/*
作用域:针对于所有会话(连接)有效,但不能跨重启
*/
#①查看所有全局变量
SHOW GLOBAL VARIABLES;
#②查看满足条件的部分系统变量
SHOW GLOBAL VARIABLES LIKE '%char%';
#③查看指定的系统变量的值
SELECT @@global.autocommit;
#④为某个系统变量赋值
SET @@global.autocommit=0;
SET GLOBAL autocommit=0;
#2》会话变量
/*
作用域:针对于当前会话(连接)有效
*/
#①查看所有会话变量
SHOW SESSION VARIABLES;
#②查看满足条件的部分会话变量
SHOW SESSION VARIABLES LIKE '%char%';
#③查看指定的会话变量的值
SELECT @@autocommit;
SELECT @@session.tx_isolation;
#④为某个会话变量赋值
SET @@session.tx_isolation='read-uncommitted';
SET SESSION tx_isolation='read-committed';
#二、自定义变量
/*
说明:变量由用户自定义,而不是系统提供的
使用步骤:
1、声明
2、赋值
3、使用(查看、比较、运算等)
*/
#1》用户变量
/*
作用域:针对于当前会话(连接)有效,作用域同于会话变量
*/
#赋值操作符:=或:=
#①声明并初始化
SET @变量名=值;
SET @变量名:=值;
SELECT @变量名:=值;
#②赋值(更新变量的值)
#方式一:
SET @变量名=值;
SET @变量名:=值;
SELECT @变量名:=值;
#方式二:
SELECT 字段 INTO @变量名
FROM 表;
#③使用(查看变量的值)
SELECT @变量名;
#2》局部变量
/*
作用域:仅仅在定义它的begin end块中有效
应用在 begin end中的第一句话
*/
#①声明
DECLARE 变量名 类型;
DECLARE 变量名 类型 【DEFAULT 值】;
#②赋值(更新变量的值)
#方式一:
SET 局部变量名=值;
SET 局部变量名:=值;
SELECT 局部变量名:=值;
#方式二:
SELECT 字段 INTO 具备变量名
FROM 表;
#③使用(查看变量的值)
SELECT 局部变量名;
案例:声明两个变量,求和并打印
用户变量
- SET @m=1;
- SET @n=1;
- SET @sum=@m+@n;
- SELECT @sum;
局部变量
- DECLARE m INT DEFAULT 1;
- DECLARE n INT DEFAULT 1;
- DECLARE SUM INT;
- SET SUM=m+n;
- SELECT SUM;
用户变量和局部变量的对比
作用域 | 定义位置 | 语法 | |
用户变量 | 当前会话 | 会话的任何地方 | 加@符号,不用指定类型 |
局部变量 | 定义它的BEGIN END中 | BEGIN END的第一句话 | 一般不用加@,需要指定类型 |
存储过程和函数:类似于java中的方法
好处:
1、提高代码的重用性
2、简化操作
存储过程
含义:一组预先编译好的SQL语句的集合,理解成批处理语句
1、提高代码的重用性
2、简化操作
3、减少了编译次数并且减少了和数据库服务器的连接次数,提高了效率
#一、创建语法
CREATE PROCEDURE 存储过程名(参数列表)
BEGIN
存储过程体(一组合法的SQL语句)
END
#注意:
/*
1、参数列表包含三部分
参数模式 参数名 参数类型
举例:
in stuname varchar(20)
参数模式:
in:该参数可以作为输入,也就是该参数需要调用方传入值
out:该参数可以作为输出,也就是该参数可以作为返回值
inout:该参数既可以作为输入又可以作为输出,也就是该参数既需要传入值,又可以返回值
2、如果存储过程体仅仅只有一句话,begin end可以省略
存储过程体中的每条sql语句的结尾要求必须加分号。
存储过程的结尾可以使用 delimiter 重新设置
语法:
delimiter 结束标记
案例:
delimiter $
*/
#二、调用语法
CALL 存储过程名(实参列表);
#--------------------------------案例演示-----------------------------------
#1.空参列表
#案例:插入到admin表中五条记录
SELECT * FROM admin;
DELIMITER $
CREATE PROCEDURE myp1()
BEGIN
INSERT INTO admin(username,`password`)
VALUES('john1','0000'),('lily','0000'),('rose','0000'),('jack','0000'),('tom','0000');
END $
#调用
CALL myp1()$
#2.创建带in模式参数的存储过程
#案例1:创建存储过程实现 根据女神名,查询对应的男神信息
CREATE PROCEDURE myp2(IN beautyName VARCHAR(20))
BEGIN
SELECT bo.*
FROM boys bo
RIGHT JOIN beauty b ON bo.id = b.boyfriend_id
WHERE b.name=beautyName;
END $
#调用
CALL myp2('柳岩')$
#案例2 :创建存储过程实现,用户是否登录成功
CREATE PROCEDURE myp4(IN username VARCHAR(20),IN PASSWORD VARCHAR(20))
BEGIN
DECLARE result INT DEFAULT 0;#声明并初始化
SELECT COUNT(*) INTO result#赋值
FROM admin
WHERE admin.username = username
AND admin.password = PASSWORD;
SELECT IF(result>0,'成功','失败');#使用
END $
#调用
CALL myp3('张飞','8888')$
#3.创建out 模式参数的存储过程
#案例1:根据输入的女神名,返回对应的男神名
CREATE PROCEDURE myp6(IN beautyName VARCHAR(20),OUT boyName VARCHAR(20))
BEGIN
SELECT bo.boyname INTO boyname
FROM boys bo
RIGHT JOIN
beauty b ON b.boyfriend_id = bo.id
WHERE b.name=beautyName ;
END $
#案例2:根据输入的女神名,返回对应的男神名和魅力值
CREATE PROCEDURE myp7(IN beautyName VARCHAR(20),OUT boyName VARCHAR(20),OUT usercp INT)
BEGIN
SELECT boys.boyname ,boys.usercp INTO boyname,usercp
FROM boys
RIGHT JOIN
beauty b ON b.boyfriend_id = boys.id
WHERE b.name=beautyName ;
END $
#调用
CALL myp7('小昭',@name,@cp)$
SELECT @name,@cp$
#4.创建带inout模式参数的存储过程
#案例1:传入a和b两个值,最终a和b都翻倍并返回
CREATE PROCEDURE myp8(INOUT a INT ,INOUT b INT)
BEGIN
SET a=a*2;
SET b=b*2;
END $
#调用
SET @m=10$
SET @n=20$
CALL myp8(@m,@n)$
SELECT @m,@n$
#三、删除存储过程
#语法:drop procedure 存储过程名
DROP PROCEDURE p1;
DROP PROCEDURE p2,p3;#×
#四、查看存储过程的信息
DESC myp2;×
SHOW CREATE PROCEDURE myp2;
函数
含义:一组预先编译好的SQL语句的集合,理解成批处理语句
1、提高代码的重用性
2、简化操作
3、减少了编译次数并且减少了和数据库服务器的连接次数,提高了效率
区别:
存储过程:可以有0个返回,也可以有多个返回,适合做批量插入、批量更新
函数:有且仅有1 个返回,适合做处理数据后返回一个结果
#一、创建语法
CREATE FUNCTION 函数名(参数列表) RETURNS 返回类型
BEGIN
函数体
END
/*
注意:
1.参数列表 包含两部分:
参数名 参数类型
2.函数体:肯定会有return语句,如果没有会报错
如果return语句没有放在函数体的最后也不报错,但不建议
return 值;
3.函数体中仅有一句话,则可以省略begin end
4.使用 delimiter语句设置结束标记
*/
#二、调用语法
SELECT 函数名(参数列表)
#------------------------------案例演示----------------------------
#1.无参有返回
#案例:返回公司的员工个数
CREATE FUNCTION myf1() RETURNS INT
BEGIN
DECLARE c INT DEFAULT 0;#定义局部变量
SELECT COUNT(*) INTO c#赋值
FROM employees;
RETURN c;
END $
SELECT myf1()$
#2.有参有返回
#案例1:根据员工名,返回它的工资
CREATE FUNCTION myf2(empName VARCHAR(20)) RETURNS DOUBLE
BEGIN
SET @sal=0;#定义用户变量
SELECT salary INTO @sal #赋值
FROM employees
WHERE last_name = empName;
RETURN @sal;
END $
SELECT myf2('k_ing') $
#案例2:根据部门名,返回该部门的平均工资
CREATE FUNCTION myf3(deptName VARCHAR(20)) RETURNS DOUBLE
BEGIN
DECLARE sal DOUBLE ;
SELECT AVG(salary) INTO sal
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE d.department_name=deptName;
RETURN sal;
END $
SELECT myf3('IT')$
#三、查看函数
SHOW CREATE FUNCTION myf3;
#四、删除函数
DROP FUNCTION myf3;
#案例
#一、创建函数,实现传入两个float,返回二者之和
CREATE FUNCTION test_fun1(num1 FLOAT,num2 FLOAT) RETURNS FLOAT
BEGIN
DECLARE SUM FLOAT DEFAULT 0;
SET SUM=num1+num2;
RETURN SUM;
END $
SELECT test_fun1(1,2)$
顺序、分支、循环
一、分支结构
1.if函数
语法:if(条件,值1,值2)
功能:实现双分支
应用在begin end中或外面
#2.case结构
/*
语法:
情况1:类似于switch
case 变量或表达式
when 值1 then 语句1;
when 值2 then 语句2;
...
else 语句n;
end
情况2:
case
when 条件1 then 语句1;
when 条件2 then 语句2;
...
else 语句n;
end
应用在begin end 中或外面
*/
#3.if结构
/*
语法:
if 条件1 then 语句1;
elseif 条件2 then 语句2;
....
else 语句n;
end if;
功能:类似于多重if
只能应用在begin end 中
*/
#案例1:创建函数,实现传入成绩,如果成绩>90,返回A,如果成绩>80,返回B,如果成绩>60,返回C,否则返回D
CREATE FUNCTION test_if(score FLOAT) RETURNS CHAR
BEGIN
DECLARE ch CHAR DEFAULT 'A';
IF score>90 THEN SET ch='A';
ELSEIF score>80 THEN SET ch='B';
ELSEIF score>60 THEN SET ch='C';
ELSE SET ch='D';
END IF;
RETURN ch;
END $
SELECT test_if(87)$
#案例2:创建存储过程,如果工资<2000,则删除,如果5000>工资>2000,则涨工资1000,否则涨工资500
CREATE PROCEDURE test_if_pro(IN sal DOUBLE)
BEGIN
IF sal<2000 THEN DELETE FROM employees WHERE employees.salary=sal;
ELSEIF sal>=2000 AND sal<5000 THEN UPDATE employees SET salary=salary+1000 WHERE employees.`salary`=sal;
ELSE UPDATE employees SET salary=salary+500 WHERE employees.`salary`=sal;
END IF;
END $
CALL test_if_pro(2100)$
#案例1:创建函数,实现传入成绩,如果成绩>90,返回A,如果成绩>80,返回B,如果成绩>60,返回C,否则返回D
CREATE FUNCTION test_case(score FLOAT) RETURNS CHAR
BEGIN
DECLARE ch CHAR DEFAULT 'A';
CASE
WHEN score>90 THEN SET ch='A';
WHEN score>80 THEN SET ch='B';
WHEN score>60 THEN SET ch='C';
ELSE SET ch='D';
END CASE;
RETURN ch;
END $
SELECT test_case(56)$
#二、循环结构
/*
分类:
while、loop、repeat
循环控制:
iterate类似于 continue,继续,结束本次循环,继续下一次
leave 类似于 break,跳出,结束当前所在的循环
*/
#1.while
/*
语法:
【标签:】while 循环条件 do
循环体;
end while【 标签】;
联想:
while(循环条件){
循环体;
}
*/
#2.loop
/*
语法:
【标签:】loop
循环体;
end loop 【标签】;
可以用来模拟简单的死循环
*/
#3.repeat
/*
语法:
【标签:】repeat
循环体;
until 结束循环的条件
end repeat 【标签】;
*/
#1.没有添加循环控制语句
#案例:批量插入,根据次数插入到admin表中多条记录
DROP PROCEDURE pro_while1$
CREATE PROCEDURE pro_while1(IN insertCount INT)
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i<=insertCount DO
INSERT INTO admin(username,`password`) VALUES(CONCAT('Rose',i),'666');
SET i=i+1;
END WHILE;
END $
CALL pro_while1(100)$
/*
int i=1;
while(i<=insertcount){
//插入
i++;
}
*/
#2.添加leave语句
#案例:批量插入,根据次数插入到admin表中多条记录,如果次数>20则停止
TRUNCATE TABLE admin$
DROP PROCEDURE test_while1$
CREATE PROCEDURE test_while1(IN insertCount INT)
BEGIN
DECLARE i INT DEFAULT 1;
a:WHILE i<=insertCount DO
INSERT INTO admin(username,`password`) VALUES(CONCAT('xiaohua',i),'0000');
IF i>=20 THEN LEAVE a;
END IF;
SET i=i+1;
END WHILE a;
END $
CALL test_while1(100)$
#3.添加iterate语句
#案例:批量插入,根据次数插入到admin表中多条记录,只插入偶数次
TRUNCATE TABLE admin$
DROP PROCEDURE test_while1$
CREATE PROCEDURE test_while1(IN insertCount INT)
BEGIN
DECLARE i INT DEFAULT 0;
a:WHILE i<=insertCount DO
SET i=i+1;
IF MOD(i,2)!=0 THEN ITERATE a;
END IF;
INSERT INTO admin(username,`password`) VALUES(CONCAT('xiaohua',i),'0000');
END WHILE a;
END $
CALL test_while1(100)$
/*
int i=0;
while(i<=insertCount){
i++;
if(i%2==0){
continue;
}
插入
}
*/
流程控制经典案例:
- /*一、已知表stringcontent
- 其中字段:
- id 自增长
- content varchar(20)
- 向该表插入指定个数的,随机的字符串
- */
- DROP TABLE IF EXISTS stringcontent;
- CREATE TABLE stringcontent(
- id INT PRIMARY KEY AUTO_INCREMENT,
- content VARCHAR(20)
-
- );
- DELIMITER $
- CREATE PROCEDURE test_randstr_insert(IN insertCount INT)
- BEGIN
- DECLARE i INT DEFAULT 1;
- DECLARE str VARCHAR(26) DEFAULT 'abcdefghijklmnopqrstuvwxyz';
- DECLARE startIndex INT;#代表初始索引
- DECLARE len INT;#代表截取的字符长度
- WHILE i<=insertcount DO
- SET startIndex=FLOOR(RAND()*26+1);#代表初始索引,随机范围1-26
- SET len=FLOOR(RAND()*(20-startIndex+1)+1);#代表截取长度,随机范围1-(20-startIndex+1)
- INSERT INTO stringcontent(content) VALUES(SUBSTR(str,startIndex,len));
- SET i=i+1;
- END WHILE;
-
- END $
-
- CALL test_randstr_insert(10)$
含义:
一种限制,用于限制表中的数据,为了保证表中的数据的准确和可靠性
分类:六大约束
NOT NULL:非空,用于保证该字段的值不能为空
比如姓名、学号等
DEFAULT:默认,用于保证该字段有默认值
比如性别
PRIMARY KEY:主键,用于保证该字段的值具有唯一性,并且非空
比如学号、员工编号等
UNIQUE:唯一,用于保证该字段的值具有唯一性,可以为空
比如座位号
CHECK:检查约束【mysql中不支持】
比如年龄、性别
FOREIGN KEY:外键,用于限制两个表的关系,用于保证该字段的值必须来自于主表的关联列的值
在从表添加外键约束,用于引用主表中某列的值
比如学生表的专业编号,员工表的部门编号,员工表的工种编号
添加约束的时机:
1.创建表时
2.修改表时
约束的添加分类:
列级约束:
六大约束语法上都支持,但外键约束没有效果
表级约束:
除了非空、默认,其他的都支持
主键和唯一的大对比:
保证唯一性 | 是否允许为空 | 一个表中可以有多少个 | 是否允许组合 | |
---|---|---|---|---|
主键 | √ | × | 至多有1个 | √,但不推荐 |
唯一 | √ | √ | 可以有多个 | √,但不推荐 |
外键:
1、要求在从表设置外键关系
2、从表的外键列的类型和主表的关联列的类型要求一致或兼容,名称无要求
3、主表的关联列必须是一个key(一般是主键或唯一)
4、插入数据时,先插入主表,再插入从表
删除数据时,先删除从表,再删除主表
CREATE TABLE 表名(
字段名 字段类型 列级约束,
字段名 字段类型,
表级约束
)
CREATE DATABASE students;
1.添加列级约束
语法:
直接在字段名和类型后面追加约束类型即可。
只支持:默认、非空、主键、唯一
- USE students;
- DROP TABLE stuinfo;
- CREATE TABLE stuinfo(
- id INT PRIMARY KEY,#主键
- stuName VARCHAR(20) NOT NULL UNIQUE,#非空
- gender CHAR(1) CHECK(gender='男' OR gender ='女'),#检查
- seat INT UNIQUE,#唯一
- age INT DEFAULT 18,#默认约束
- majorId INT REFERENCES major(id)#外键
-
- );
- CREATE TABLE major(
- id INT PRIMARY KEY,
- majorName VARCHAR(20)
- );
查看stuinfo中的所有索引,包括主键、外键、唯一
SHOW INDEX FROM stuinfo;
2.添加表级约束
语法:在各个字段的最下面
【constraint 约束名】 约束类型(字段名)
- DROP TABLE IF EXISTS stuinfo;
- CREATE TABLE stuinfo(
- id INT,
- stuname VARCHAR(20),
- gender CHAR(1),
- seat INT,
- age INT,
- majorid INT,
-
- CONSTRAINT pk PRIMARY KEY(id),#主键
- CONSTRAINT uq UNIQUE(seat),#唯一键
- CONSTRAINT ck CHECK(gender ='男' OR gender = '女'),#检查
- CONSTRAINT fk_stuinfo_major FOREIGN KEY(majorid) REFERENCES major(id)#外键
-
- );
SHOW INDEX FROM stuinfo;
通用的写法:★
- CREATE TABLE IF NOT EXISTS stuinfo(
- id INT PRIMARY KEY,
- stuname VARCHAR(20),
- sex CHAR(1),
- age INT DEFAULT 18,
- seat INT UNIQUE,
- majorid INT,
- CONSTRAINT fk_stuinfo_major FOREIGN KEY(majorid) REFERENCES major(id)
-
- );
1、添加列级约束
alter table 表名 modify column 字段名 字段类型 新约束;
2、添加表级约束
alter table 表名 add 【constraint 约束名】 约束类型(字段名) 【外键的引用】;
- DROP TABLE IF EXISTS stuinfo;
- CREATE TABLE stuinfo(
- id INT,
- stuname VARCHAR(20),
- gender CHAR(1),
- seat INT,
- age INT,
- majorid INT
- )
- DESC stuinfo;
3.添加非空约束
ALTER TABLE stuinfo MODIFY COLUMN stuname VARCHAR(20) NOT NULL;
4.添加默认约束
ALTER TABLE stuinfo MODIFY COLUMN age INT DEFAULT 18;
5.添加主键
- #①列级约束
- ALTER TABLE stuinfo MODIFY COLUMN id INT PRIMARY KEY;
- #②表级约束
- ALTER TABLE stuinfo ADD PRIMARY KEY(id);
6.添加唯一
- #①列级约束
- ALTER TABLE stuinfo MODIFY COLUMN seat INT UNIQUE;
- #②表级约束
- ALTER TABLE stuinfo ADD UNIQUE(seat);
7.添加外键
ALTER TABLE stuinfo ADD CONSTRAINT fk_stuinfo_major FOREIGN KEY(majorid) REFERENCES major(id);
1.删除非空约束
ALTER TABLE stuinfo MODIFY COLUMN stuname VARCHAR(20) NULL;
2.删除默认约束
ALTER TABLE stuinfo MODIFY COLUMN age INT ;
3.删除主键
ALTER TABLE stuinfo DROP PRIMARY KEY;
4.删除唯一
ALTER TABLE stuinfo DROP INDEX seat;
5.删除外键
- ALTER TABLE stuinfo DROP FOREIGN KEY fk_stuinfo_major;
-
- SHOW INDEX FROM stuinfo;
1.向表emp2的id列中添加PRIMARY KEY约束(my_emp_id_pk)
- ALTER TABLE emp2 MODIFY COLUMN id INT PRIMARY KEY;
- ALTER TABLE emp2 ADD CONSTRAINT my_emp_id_pk PRIMARY KEY(id);
2. 向表dept2的id列中添加PRIMARY KEY约束(my_dept_id_pk)
3. 向表emp2中添加列dept_id,并在其中定义FOREIGN KEY约束,与之相关联的列是dept2表中的id列。
- ALTER TABLE emp2 ADD COLUMN dept_id INT;
- ALTER TABLE emp2 ADD CONSTRAINT fk_emp2_dept2 FOREIGN KEY(dept_id) REFERENCES dept2(id);
对比:
位置 | 支持的约束类型 | 是否可以起约束名 | |
---|---|---|---|
列级约束 | 列的后面 | 语法都支持,但外键没有效果 | 不可以 |
表级约束 | 所有列的下面 | 默认和非空不支持,其他支持 | 可以(主键没有效果) |
又称为自增长列
含义:可以不用手动的插入值,系统提供默认的序列值
特点:
1、标识列必须和主键搭配吗?不一定,但要求是一个key
2、一个表可以有几个标识列?至多一个!
3、标识列的类型只能是数值型
4、标识列可以通过 SET auto_increment_increment=3;设置步长
可以通过 手动插入值,设置起始值
- DROP TABLE IF EXISTS tab_identity;
- CREATE TABLE tab_identity(
- id INT ,
- NAME FLOAT UNIQUE AUTO_INCREMENT,
- seat INT
-
-
- );
truncate表:
TRUNCATE TABLE tab_identity;
- INSERT INTO tab_identity(id,NAME) VALUES(NULL,'john');
- INSERT INTO tab_identity(NAME) VALUES('lucy');
- SELECT * FROM tab_identity;
-
- SHOW VARIABLES LIKE '%auto_increment%';
-
- SET auto_increment_increment=3;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。