<MySQL>入门一 查询 DQL
1. 数据库表
1.1 员工表
Create Table 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
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');
1.2 部门表
Create Table 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 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);
1.3 工作表
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 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);
1.4 位置表
Create Table 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 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');
2. 基础查询(select)
2.1 查询单个字段
SELECT last_name FROM employees
2.2 查询多个字段
SELECT last_name,email,salary FROM employees
2.3 查询所有字段
SELECT * FROM employees
2.4 查询常量值、表达式
SELECT 100;
SELECT 'john';
SELECT 100*8;
SELECT 100%98;
2.5 查询函数
SELECT VERSION(); -- 查询数据库版本
2.6 起别名(如果查询的字段有重名,可以使用起别名区分,别名中有特殊符号,用引号引起来)
SELECT last_name AS 姓,first_name AS 名 FROM employees;
SELECT last_name 姓,first_name 名 FROM employees;
SELECT salary AS 'out put' FROM employees;
2.7 去重(distinct)
# 查询员工表中涉及到的所有部门编号,需要去除重复
SELECT DISTINCT department_id FROM employees;
2.8 +号的作用(concat、ifnull)
/*
java中+号
1.运算符,两个都为数值
2.连接符,只要有一个操作数为字符串 mysql中
仅仅:运算符
*/
SELECT 100+90; -- 做加法运算
SELECT ''+90; -- 其中一方为字符串,试图将字符串转换成数值型,如果成功,继续做加法
SELECT 'john'+90; -- 如果转换失败,则将字符串变为0,再运算
SELECT NULL+10; -- 其中一个为null,则结果肯定为null
# 将员工的姓和名连接成一个字段,并显示为姓名
SELECT CONCAT('a','b','c') AS 结果;
SELECT CONCAT(last_name,first_name) AS 姓名 FROM employees;
-- concat中拼接null值为null
SELECT CONCAT(100,NULL);
-- ifnull(需要转换的字段,转换后的值)
SELECT IFNULL(`commission_pct`,0) 奖金率,`commission_pct` FROM employees;
3. 条件查询
where
条件运算符:>,<, = ,!=, <>, >= ,<=
逻辑运算符:and(&&) ,or(||), not(!)
模糊查询:like,between and,in,is null
3.1 简单的条件查询
# 查询工资>12000的员工信息 ( > )
SELECT * FROM employees WHERE salary > 12000; # 查询部门编号不等于90号的员工名和部门编号 ( != <> )
SELECT last_name 名字,`department_id` 部门编号 FROM employees WHERE `department_id` <> 90; # 查询工资在10000~20000之间的员工名,工资以及奖金 ( and )
SELECT last_name 名字,salary 工资,`commission_pct` 奖金 FROM employees WHERE salary >10000 AND salary <20000; # 查询部门编号不在90到110之间,或者工资高于15000的员工信息 ( OR > < )
SELECT * FROM employees WHERE department_id >110 OR department_id < 90 OR salary > 15000
3.2 模糊查询
like
-- 通配符: % 任意多个字符(包括空字符)
-- _ 任意单个字符
-- 查询员工名字包含a的员工信息
SELECT * FROM employees WHERE last_name LIKE '%a%'; -- 查询员工第三个字符为e,第五个字符为a
SELECT * FROM employees WHERE last_name LIKE '__n_l%' -- 查询第二个字符为_的员工名
SELECT * FROM employees WHERE last_name LIKE '_\_%' -- \ 转义
SELECT * FROM employees WHERE last_name LIKE '_$_%' ESCAPE '$' -- escape '任意字符' 进行转义 推荐
3.3 其他查询
between and
-- 查询员工编号在100到120之间的员工信息
-- 包含临界值
-- 两个临界值不要颠倒顺序
SELECT * FROM employees WHERE employee_id BETWEEN 100 AND 120;
SELECT * FROM employees WHERE employee_id >=100 AND employee_id<=120;
in
-- 查询员工工种编号是IT_PROG、AD_VP、AD_PRES之间
-- in:判断某字段的值是否属于in列表中的某一项 SELECT * FROM employees WHERE job_id IN ('IT_PROG','AD_VP','AD_PRES');
is null
-- 查询没有奖金的
-- =或<>不能判断 null 值
-- 所以需要使用 is null ,is not null
SELECT * FROM employees WHERE commission_pct IS NULL; -- 查询有奖金的
SELECT * FROM employees WHERE commission_pct IS NOT NULL;
安全等于
-- 查询没有奖金的
-- 安全等于:<=>
-- 可以当 is 或者 = 使用
SELECT * FROM employees WHERE commission_pct <=> NULL; SELECT * FROM employees WHERE salary <=> 12000;
4. 排序查询
order by
-- select 查询字段 from 表名 where 筛选条件 order by [ASC,DESC]
-- asc 升序, desc 降序 ,不写默认是asc
-- order by 子句 支持单个字段,多个字段(,隔开),表达式,函数,别名
-- order by 一般放最后面,除了 limit -- 查询员工信息 工资由高到低
SELECT * FROM employees ORDER BY salary DESC;
-- 查询员工信息 工资由低到高 默认asc
SELECT * FROM employees ORDER BY salary; -- 查询部门编号>=90的员工信息,按入职时间排序
SELECT * FROM employees WHERE department_id >= 90 ORDER BY hiredate; -- 按年薪由高到低 显示员工信息及年薪
SELECT *,salary*12*(1+IFNULL('commssion_pct',0)) 年薪 FROM employees ORDER BY salary*12*(1+IFNULL('commssion_pct',0)) ;
-- order by 后面支持别名
SELECT *,salary*12*(1+IFNULL('commssion_pct',0)) 年薪 FROM employees ORDER BY 年薪 ; -- 按照名字字母的长度 排序
-- length() 函数
SELECT * FROM employees ORDER BY LENGTH(last_name); -- 查询员工信息,先按工资升序排序,再按员工编号降序排序
SELECT * FROM employees ORDER BY salary ASC, employee_id DESC;
小练习
-- 查询员工姓名,部门编号,年薪,按年薪降序,姓名升序
SELECT last_name 姓名,department_id 部门编号,salary*12*IFNULL(commission_pct,0) 年薪
FROM employees ORDER BY 年薪 DESC,姓名 ASC -- 选择工资不在8K到17K的员工姓名和工资,按工资降序
SELECT last_name 姓名,salary 工资 FROM employees WHERE salary NOT BETWEEN 8000 AND 17000 ORDER BY 工资 DESC -- 查询邮件中包含e的员工,并且按邮箱字节降序, 再按部门号升序
SELECT * FROM employees WHERE `email` LIKE '%e%' ORDER BY LENGTH(email) DESC,department_id;
5.常见函数
将一组逻辑封装在方法中,对外暴露方法名
1.隐藏了实现细节
2.提高代码的重用性
函数名(实参列表)
分类:
1.单行函数:concat 、length 、ifnull等
2.分组函数:做统计使用,聚合函数。
字符函数
-- length 获取参数值的字节个数
SELECT LENGTH('maple');
-- utf-8中文三个字节,gbk中文字符2个字节
SELECT LENGTH('麦克雷'); -- concat 拼接字符串
SELECT CONCAT (last_name,'_',first_name) 姓名 FROM employees; -- upper、lower
SELECT UPPER('maple');
SELECT LOWER('Maple');
-- 将姓变大写,名变小写
SELECT CONCAT(UPPER(last_name),'_',LOWER(first_name)) FROM employees; -- substr、substring
-- mysql 索引从1开始,包括索引位置,例如4包括'在'
SELECT SUBSTR('麦克雷在高台读午时已到',4); -- 在高台读午时已到
-- (str,index,len) 指定索引处,截取字符长度
SELECT SUBSTR('麦克雷在高台读午时已到',1,3); -- 麦克雷
-- 案例:姓名中首字母字符大写,其他小写,然后用_拼接
SELECT CONCAT(UPPER(SUBSTR(last_name,1,1)),'_',LOWER(SUBSTR(last_name,2))) FROM employees; -- instr 子串在字符串中的第一次出现索引,如果找不到返回0
SELECT INSTR('双眼失明丝毫不影响我追捕敌人','追捕敌人'); -- -- trim
SELECT LENGTH(TRIM(' 源氏 ')) AS out_put ; --
SELECT TRIM('a' FROM 'aaaaaaaaa天aaa使aaaaaaaa'); -- 天aaa使 -- lpad 用指定字符实现左填充指定长度
SELECT LPAD('全场最佳',10,''); -- 666666全场最佳
-- rpad 用指定字符实现左填充指定长度
SELECT RPAD('全场最佳',10,''); -- 全场最佳666666 -- replace 替换字符
SELECT REPLACE('源氏开大杀杀杀杀杀','杀','送'); -- 源氏开大送送送送送
数学函数
-- round 四舍五入
SELECT ROUND(1.65); --
SELECT ROUND(1.4); --
SELECT ROUND(-1.4); -- -1
-- 保留位数
SELECT ROUND(1.567,2); -- 1.57 -- ceil 向上取整 返回大于等于该参数的最小整数
SELECT CEIL(1.00001); --
SELECT CEIL(-1.00001); -- -1 -- floor 向下取整
SELECT FLOOR(9.99); --
SELECT FLOOR(-0.15); -- -1 -- truncat 小数点后截断几位
SELECT TRUNCATE(1.6999,1); -- 1.6 -- mod取余
SELECT MOD(10,3); --
日期函数
-- now 返回当前系统日期+时间
SELECT NOW(); -- 2018-12-07 17:18:57 -- curdate 返回当前系统日期,不包含时间
SELECT CURDATE(); -- 2018-12-07 -- curtime 返回当前时间,不包含日期
SELECT CURTIME(); -- 17:20:10 -- 可以获取指定的部分,年、月、日、时、分、秒
SELECT YEAR(NOW()) 年; --
SELECT YEAR('1998-10-12') 年; --
SELECT YEAR(hiredate) FROM employees; SELECT MONTH(NOW()) 月; -- 12
SELECT MONTHNAME(NOW()) 月; -- December -- str_to_date 将字符通过指定的格式转换成日期
SELECT STR_TO_DATE('1992-2-3','%Y-%c-%d');
SELECT * FROM employees WHERE hiredate = '1992-4-3';
-- 但是前台可能传过来的值为 3-4-1992 ,此时需要格式化字符串
SELECT * FROM employees WHERE hiredate = STR_TO_DATE('4-3-1992','%m-%d-%Y'); -- date_format 将日期转换为字符
SELECT DATE_FORMAT(NOW(),'%Y年%m月%d日');
-- 查询有奖金的员工名和入职日期(xx月/xx日 xx年)
SELECT last_name,DATE_FORMAT(hiredate,'%m月/%d %Y') 入职日期 FROM employees WHERE commission_pct IS NOT NULL;
-- datediff 日期相减
SELECT DATEDIFF(NOW(),'1992-3-6'); --9973
其他函数
-- 查看mysql版本
SELECT VERSION(); -- 查看当前选择的数据库
SELECT DATABASE(); -- 查看当前用户
SELECT USER();
流程控制函数
-- if 函数
SELECT IF(10>5,'大','小'); -- case 函数 使用1
/*
case 需要判断的字段或表达式
when 常量1 then 要显示的值1或语句1;
when 常量2 then 要显示的值1或语句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 新工资
FROM employees; -- case 函数 使用2
/*
case
when 条件1 then 要显示的值1或 语句1;
...
else 要显示的值n 或语句 n
end
区别在case 后面是否加语句
*/
/*
查询员工的工资情况
如果工资>20000,显示A级别
如果工资>15000,显示B级别
如果工资>10000,显示C级别
否则,显示D级别
*/ SELECT last_name , salary,
CASE
WHEN salary>20000 THEN 'A'
WHEN salary>15000 THEN 'B'
WHEN salary>10000 THEN 'C'
ELSE 'D'
END 工资级别
FROM employees;
分组函数
sum avg max min count
-- 简单使用
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) 和, ROUND(AVG(salary),2) 平均,MIN(salary) 最小, MAX(salary) 最大 ,COUNT(salary) 总数 FROM employees; -- 支持哪些参数类型
/*
1.sum,avg一般处理数值型
max,min,count可以处理任何类型
2.以上分组函数都忽略null值
3.可以和distinct搭配 去重
4.一般用count(*)做统计行数
5.和分组函数一同查询的字段要求是group by后的字段
*/
-- 去除了重复的工资再求和
SELECT SUM(DISTINCT salary) ,SUM(salary) FROM employees;
-- 计算有多少种工资
SELECT COUNT(DISTINCT salary),COUNT(salary) FROM employees; -- count详细使用
-- 计算总行数
SELECT COUNT(*) FROM employees;
-- 相当于在表加了一个全是1的字段,然后计算总数。
-- count()里可以随便写。
-- 在myisam引擎下,count(*)效率最高,默认带有计数器
-- 在innodb下,count(*)和count(1)差不多,比count(字段)高一些,因为要判断非空
SELECT COUNT(1) FROM employees;
分组查询(group by)
-- 分组函数
/*
select 分组函数,列(出现在gourp by后面)
from 表
where 筛选条件
group by 分组的列表
order by 子句 查询的列表特殊,必须是分组函数和group by后的字段 分组前筛选:from 哪个表 group by 前面 where
分组后筛选:having,对分组后的结果集进行筛选 group by 后面 having 分组函数做条件肯定放在having中
能用分组前筛选,就优先考虑分组前筛选 group by 支持单个字段分组,也支持多个字段分组(多个字段用逗号隔开,没有顺序要求)
也支持表达式,函数(用的较少)
也可以添加排序
*/ -- 查询每个工种的最高工资
SELECT MAX(salary),job_id FROM employees GROUP BY job_id; -- 查询每个位置有多少部门
SELECT COUNT(*),location_id FROM departments GROUP BY location_id; -- 查询邮箱中包含a字符,每个部门的平均工资
SELECT AVG(salary),department_id FROM employees WHERE email LIKE '%a%' GROUP BY department_id; -- 查询有奖金的每个领导下的员工最高工资
SELECT MAX(salary) 最高工资,manager_id 领导 FROM employees WHERE commission_pct IS NOT NULL GROUP BY manager_id; -- 查询哪个部门的员工个数大于2
-- 使用having,对分组后的数据再进行筛选
SELECT COUNT(*),department_id FROM employees GROUP BY department_id HAVING COUNT(*) >2 ; -- 查询每个工种有奖金的员工,最高工资>12000的工种编号和最高工资
SELECT job_id,MAX(salary) FROM employees WHERE commission_pct IS NOT NULL GROUP BY job_id HAVING MAX(salary)>12000; -- 查询领导编号>102的每个领导手下的最低工资>5000的领导编号是哪个,以及最低工资
SELECT MIN(salary),manager_id FROM employees WHERE manager_id > 102 GROUP BY manager_id HAVING MIN(salary) > 5000; -- 按表达式或函数筛选
-- group by ,having 支持别名
-- 按员工姓名的长度分组,查询每一组的员工个数,筛选员工个数>5的有哪些
SELECT COUNT(*) 员工个数,LENGTH(last_name) 名字长度 FROM employees GROUP BY 名字长度 HAVING 员工个数>5; -- 查询每个部门每个工种的员工的平均工资
SELECT AVG(salary),department_id,job_id FROM employees GROUP BY department_id,job_id; -- 查询每个部门每个工种的员工的平均工资 并且按平均工资排序
SELECT AVG(salary),department_id,job_id FROM employees GROUP BY department_id,job_id ORDER BY salary;
6. 多表查询
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','',NULL,8),(2,'苍老师','女','1987-12-30 00:00:00','',NULL,9),(3,'Angelababy','女','1989-02-03 00:00:00','',NULL,3),(4,'热巴','女','1993-02-03 00:00:00','',NULL,2),(5,'周冬雨','女','1992-02-03 00:00:00','',NULL,9),(6,'周芷若','女','1988-02-03 00:00:00','',NULL,1),(7,'岳灵珊','女','1987-12-30 00:00:00','',NULL,9),(8,'小昭','女','1989-02-03 00:00:00','',NULL,1),(9,'双儿','女','1993-02-03 00:00:00','',NULL,9),(10,'王语嫣','女','1992-02-03 00:00:00','',NULL,4),(11,'夏雪','女','1993-02-03 00:00:00','',NULL,9),(12,'赵敏','女','1992-02-03 00:00:00','',NULL,1);
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 NAME,boyName FROM boys,beauty; /*
出现笛卡尔积,48号
即:select count(*) from boys -> 4
select count(*) from beauty -> 12
表1 m行,表2 n行,笛卡尔积:m*n行 发生原因:没有有效的连接条件
如何避免:添加有效的连接条件 分类:
按年代分类:
sql92标准:仅仅支持内连接,外连接支持一部分,但是支持的不好
sql99标准(推荐):支持下面三张连接,除了全外连接
按功能分类:
内连接:
等值连接
非等值连接
自连接
外连接:
左外连接
右外连接
全外连接
交叉连接:
*/ SELECT beauty.NAME,boys.boyName FROM boys,beauty WHERE boys.id = beauty.boyfriend_id;
sql92语法
等值连接
-- 等值连接
/* 1.多表等值连接的结果为多表的交集部分
2.n表连接,至少需要n-1个连接条件
3.多表的顺序没有要求
4.一般需要为表起别名
5.可以搭配前面的所有子句,比如排序,分组,筛选 */ -- 1.查询员工名和对应的部门名
SELECT last_name,department_name
FROM employees e,departments d
WHERE e.`department_id` = d.`department_id`; -- 2.查询员工号,工种号,工种名
SELECT e.`employee_id`,e.`job_id`,j.`job_title`
FROM employees e,jobs j
WHERE e.`job_id` = j.`job_id`; -- 3.查询有奖金的员工名,部门名
SELECT e.`last_name`,d.`department_name`,e.`commission_pct`
FROM employees e,departments d
WHERE e.`department_id` = d.`department_id`
AND e.`commission_pct` IS NOT NULL; -- 4.查询城市名中第二个字符为o的部门名和城市名
SELECT d.`department_name`,l.`city`
FROM departments d,locations l
WHERE l.`city` LIKE '_o%'
AND d.`location_id`=l.`location_id` -- 5.查询每个城市的部门个数
SELECT COUNT(*) 部门个数,l.`city`
FROM departments d,locations l
WHERE d.`location_id` = l.`location_id`
GROUP BY l.`city`; -- 6.查询有奖金的每个部门的部门名和部门领导编号和该部门的最低工资
SELECT d.`department_name`,d.`manager_id`,MIN(e.salary)
FROM employees e,departments d
WHERE e.`commission_pct` IS NOT NULL
AND e.`department_id` = d.`department_id`
GROUP BY d.`department_id`,e.`department_id`; -- 7.查询每个工种的工种名和员工个数,并且按员工个数降序
SELECT j.`job_title`,COUNT(*) 员工个数
FROM employees e,jobs j
WHERE e.`job_id`=j.`job_id`
GROUP BY e.`job_id`
ORDER BY 员工个数; -- 三表连接
-- 查询员工名,部门名和所在的城市
SELECT e.`last_name`,d.`department_name`,l.`city`
FROM employees e,departments d,locations l
WHERE e.`department_id` = d.`department_id` AND d.`location_id` = l.`location_id`;
非等值连接
-- 工资级别表
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);
-- 非等值连接 -- 查询员工的工资和工资级别
SELECT e.`salary`,jg.`grade_level`
FROM employees e,job_grades jg
WHERE e.`salary` BETWEEN jg.`lowest_sal` AND jg.`highest_sal`;
自连接
-- 自连接
-- 把一张表当成两张或多张表使用,即自连接 -- 查询员工名和上级的名字
SELECT e1.`last_name` 员工名,e2.`last_name` 上级,e1.`employee_id`
FROM employees e1,employees e2
WHERE e1.`manager_id`=e2.`employee_id`;
sql99语法
-- sql99语法
/*
select 查询列表
from 表1 别名 【连接类型】
join 表2 别名
on 连接条件
where 筛选条件
group by 分组
having 筛选条件
order by 排序 分类:
内连接:inner
外连接:
左外:left [outer]
右外:right [outer]
全外:full [outer]
交叉连接: cross
*/
内连接
1.等值连接
-- 内连接 inner join on
/*
1.添加排序、分组、筛选
2.inner 可以省略
3.筛选条件放在where后面,连接条件放在onq前面,提高了分离性
4.inner join 和sql92的等值连接效果是一样的,都是查询多表的交集
*/ -- 等值连接 -- 1.查询员工名部门名
SELECT e.`last_name`,d.`department_name`
FROM employees e
INNER JOIN departments d
ON e.`department_id` = d.`department_id`; -- 2.查询名字中包含e的员工名和工种名
SELECT e.`last_name`,j.`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 COUNT(*),l.`city`
from departments d
inner join locations l
on d.`location_id`=l.`location_id`
GROUP BY l.`city`
HAVING COUNT(*)>3; -- 4.查询哪个部门的部门员工个数>3的部门名和员工个数,并按个数降序
SELECT d.`department_name`,COUNT(*)
FROM employees e
INNER JOIN departments d
ON e.`department_id` = d.`department_id`
GROUP BY d.`department_name`
HAVING COUNT(*)>3
ORDER BY COUNT(*) DESC; -- 5.查询员工名、部门名、工种名、并按部门名降序 三表连接
SELECT e.`last_name`,d.`department_name`,j.`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 d.`department_name` DESC;
2.非等值连接
-- 非等值连接 -- 查询员工的工资级别
SELECT e.`salary`,jg.`grade_level`
FROM employees e
INNER JOIN job_grades jg
ON e.`salary` BETWEEN jg.`lowest_sal` AND jg.`highest_sal`; -- 查询每个工资级别的个数>20的个数,并且排序级别降序
SELECT COUNT(*),jg.`grade_level`
FROM employees e
INNER JOIN job_grades jg
ON e.`salary` BETWEEN jg.`lowest_sal` AND jg.`highest_sal`
GROUP BY jg.`grade_level`
HAVING COUNT(*)>20
ORDER BY jg.`grade_level` DESC;
3.自连接
-- 自连接 -- 查询员工的名字和上级的名字
SELECT e.`last_name` 员工名字,m.`last_name` 上级名字
FROM employees e
INNER JOIN employees m
ON e.`manager_id` = m.`employee_id`; -- 查询员工名字包含k的员工名字和上级的名字
SELECT e.`last_name` 员工名字,m.`last_name` 上级名字
FROM employees e
INNER JOIN employees m
ON e.`manager_id` = m.`employee_id`
WHERE e.`last_name` LIKE '%k%';
外连接
-- 左外右外 /*
应用场景:查询一个表里有,另一个表没有的 特点:
1.外连接的查询结果为主表中的所有记录
如果从表中有和它匹配的,则显示匹配的值
如果从表中没有和它匹配的,则显示null
外连接查询结果=内连接结果+主表中有而从表没有的记录 2.左外连接:left左边的是主表
右外连接:right右边的是主表 3.左外和右外交换两个表的顺序,可以实现同样的效果
4.全外连接=内连接的结果+表1有表2没有的+表2有表1没有的
*/ -- 查询没有男朋友的女神名
SELECT be.name
FROM beauty be
LEFT OUTER JOIN boys bo
ON bo.id = be.boyfriend_id
WHERE bo.id IS NULL; -- 1.查询哪个部门没有员工
SELECT d.`department_name`
FROM departments d
LEFT OUTER JOIN employees e
ON d.`department_id` = e.`department_id`
WHERE e.`employee_id` IS NULL;
交叉连接
-- 交叉连接
-- 形成笛卡尔积 SELECT be.*,bo.*
FROM beauty be
CROSS JOIN boys bo;
练习
-- 练习 -- 1.查询编号>3的女神的男朋友信息,如果有则列出详细信息,如果没有用null填充
SELECT be.id,be.name,bo.*
FROM beauty be
LEFT JOIN boys bo
ON be.boyfriend_id = bo.id
WHERE be.id >3; -- 2.查询哪个城市没有部门
SELECT l.`city`
FROM locations l
LEFT JOIN departments d
ON d.`location_id` = l.`location_id`
WHERE d.`department_id` IS NULL; -- 3.查询部门名称为SAL或IT的员工信息
SELECT d.`department_name`,e.`last_name`
FROM departments d
LEFT JOIN employees e
ON d.`department_id` = e.`department_id`
WHERE d.`department_name` IN ('SAL','IT');
7.子查询
/*
子查询:
出现在其他语句的select语句,称为子查询或内查询
主查询:
外部的查询语句,称为主查询或外查询 分类:
按照查询出现的位置:
select后
仅仅支持标量子查询
from后
支持表子查询
where或having后 ☆
标量子查询 ☆
列子查询 ☆
行子查询
exists后(相关子查询)
表子查询
按照结果集的行列数不同:
标量子查询:结果集一行一列
列子查询:结果集一列多行
行子查询:结果集一行多列
表子查询:结果集一般为多行多列
*/
where having 后面:
-- where having 后面
/*
特点
1.子查询放在小括号内
2.子查询一般放在条件的右侧
3.子查询的执行优于主查询,主查询的条件用到了子查询的结果
标量子查询,一般搭配着单行操作符使用 > < >= <= <>
列子查询:一般搭配多个操作符使用 in any/some all
*/ -- 标量子查询 -- 1.谁的工资比Abel高
-- ①SELECT salary FROM employees WHERE last_name = 'Abel' 查出 Abel 的工资,是一行一列
SELECT last_name FROM employees WHERE salary > (SELECT salary FROM employees WHERE last_name = 'Abel'); -- 2.返回job_id 与141号员工相同,salary 比143号员工多的 员工姓名,job_id和工资
-- ①select job_id from employees where employee_id = 141; 一行一列
-- ②select salary from employees where employee_id = 143; 一行一列
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; 一行一列
SELECT last_name,job_id,salary FROM employees WHERE salary = (SELECT MIN(salary) FROM employees); -- 4.查询最低工资大于50号部门最低工资 的部门id和其最低工资
-- ①select min(salary) from employees where department_id = 50; 一行一列
SELECT MIN(salary),department_id FROM employees GROUP BY department_id
HAVING MIN(salary) > (SELECT MIN(salary) FROM employees WHERE department_id = 50); -- 列子查询(多行子查询) 一列多行
/*
in/not in 等于列表中任意一个
any/some 和子查询返回的某一个值比较
all 和子查询的所有值比较
*/ -- 1.返回location_id是1400或1700的部门中所有的员工姓名
-- ①select distinct department_id from departments where location_id in (1400,1700);
SELECT last_name FROM employees
WHERE department_id IN (SELECT DISTINCT department_id FROM departments WHERE location_id IN (1400,1700)); -- 2.返回其他工种中比job_id为'IT_PROG'工种任一工资低的员工的:工号,姓名,job_id和salary
-- ①select salary from employees where job_id = 'IT_PROG';
SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary <
ANY(SELECT salary FROM employees WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
-- 或者
SELECT employee_id,last_name,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 salary from employees where job_id = 'IT_PROG';
SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary <
ALL(SELECT salary FROM employees WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
-- 或者
SELECT employee_id,last_name,job_id,salary FROM employees WHERE salary <
(SELECT MIN(salary) FROM employees WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG'; -- 行子查询 (结果集为一行多列或多行多列) -- 1.查询员工编号最小并且工资最高的员工信息
SELECT * FROM employees
WHERE (employee_id,salary)=(
SELECT MIN(employee_id),MAX(salary) FROM employees
);
select 后面
-- select 后面
-- 仅仅支持标量子查询 -- 1.查询每个部门的员工个数
SELECT
d.*,
(SELECT COUNT(*) FROM employees e WHERE e.`department_id`=d.`department_id`) 员工个数
FROM departments d; -- 2.查询员工号=102的部门名
SELECT d.`department_name`
FROM departments d
WHERE d.`department_id`=(SELECT department_id FROM employees e WHERE e.employee_id = 102); SELECT (
SELECT d.department_name
FROM departments d
INNER JOIN employees e
ON d.department_id = e.department_id
WHERE e.employee_id = 102
) 部门名;
from 后面
-- from后面
-- 将子查询当成一张表,要求必须起别名 -- 查询每个部门的平均工资的工资等级
SELECT jg.`grade_level`,a.department_id,a.平均工资
FROM (SELECT AVG(salary) 平均工资,department_id FROM employees GROUP BY department_id) a
LEFT JOIN job_grades jg
ON a.平均工资 BETWEEN jg.`lowest_sal` AND jg.`highest_sal`;
exists后面(相关子查询)
-- exists后面 跟完整的查询语句
-- boolean值 当有结果返回1 ,没结果返回2
SELECT EXISTS (SELECT employee_id FROM employees);
SELECT EXISTS (SELECT employee_id FROM employees WHERE salary = 30000); -- 1.查询有员工的部门名
-- 使用exists
SELECT department_name
FROM departments d
WHERE EXISTS (
SELECT * FROM employees e WHERE e.`department_id`=d.`department_id`
);
-- 使用in
SELECT department_name
FROM departments d
WHERE d.`department_id` IN (SELECT department_id FROM employees); -- 2.查询没有女朋友的男神信息
-- exists
SELECT bo.* FROM boys bo
WHERE NOT EXISTS (SELECT be.`boyfriend_id` FROM beauty be WHERE be.`boyfriend_id`=bo.`id`); -- in
SELECT bo.* FROM boys bo WHERE bo.`id` NOT IN (SELECT `boyfriend_id` FROM beauty);
练习:
-- 1.查询和Zlotkey相同部门的员工姓名和工资
SELECT last_name,salary FROM employees
WHERE department_id =
(SELECT department_id FROM employees WHERE last_name = 'Zlotkey'); -- 2.查询工资比公司平均工资高的员工和员工号,姓名和工资,
SELECT last_name,employee_id,salary FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees); -- 3.查询各部门中工资比本部门平均工资高的员工的员工号,姓名和工资
SELECT employee_id,last_name,salary,e.department_id
FROM employees e
INNER JOIN (SELECT AVG(salary) avgs, department_id FROM employees GROUP BY department_id) d
ON e.`salary`>d.avgs AND e.`department_id`= d.department_id; -- 4.查询 姓名中包含字母u的员工 在相同部门的员工 的员工号和姓名
SELECT employee_id,last_name
FROM employees WHERE department_id IN(
SELECT DISTINCT department_id
FROM employees WHERE last_name LIKE '%u%'
); -- 5.查询在部门的location_id为1700的部门工作的员工的员工号
SELECT employee_id
FROM employees
WHERE department_id
= ANY (SELECT DISTINCT department_id FROM departments WHERE location_id = 1700); -- 6.查询管理者是King的员工姓名和工资
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 CONCAT(first_name,' ',last_name) 姓名 FROM employees WHERE salary = (SELECT MAX(salary) FROM employees);
8. 分页查询(limit offset,size) offset :起始索引从0开始,size:是显示几条
-- limit
/*
特点:
1.limit语句放在查询语句的最后
2.公式:要显示的页数是page,每页条目数是size
select 查询列表 from 表 lImit (page-1)*size,size; */
-- 查询前5条员工信息
SELECT * FROM employees LIMIT 0,5;
SELECT * FROM employees LIMIT 5; -- 查询第11条到第25条
SELECT * FROM employees LIMIT 10,15; -- 有奖金的员工信息, 并且工资较高的前10名显示出来
SELECT * FROM employees WHERE commission_pct IS NOT NULL ORDER BY salary DESC LIMIT 0,10;
综合练习
-- 1.查询工资最低的员工信息 :last_name,salary
SELECT last_name,salary
FROM employees
WHERE salary =
(SELECT MIN(salary) FROM employees); -- 2.查询平均工资最低的部门信息
SELECT *
FROM departments
WHERE department_id =
(SELECT department_id FROM employees GROUP BY department_id ORDER BY AVG(salary) ASC LIMIT 1 ); -- 3.查询平均工资最低的部门信息和该部门的平均工资
SELECT d.*,a.avgs
FROM departments d
JOIN (SELECT AVG(salary) avgs,department_id FROM employees GROUP BY department_id ORDER BY AVG(salary) LIMIT 1) a
ON d.`department_id`=a.department_id; -- 4.查询平均工资最高的job信息
SELECT * FROM jobs WHERE job_id =
(SELECT job_id FROM employees GROUP BY job_id ORDER BY AVG(salary) DESC LIMIT 1); -- 5.查询平均工资高于公司平局工资的部门有哪些
-- 我的
SELECT a.avgs,a.department_id FROM
(SELECT AVG(salary) avgs,department_id FROM employees GROUP BY department_id) a
WHERE a.avgs>
(SELECT AVG(salary) avgs FROM employees);
-- 简单的
SELECT AVG(salary),department_id FROM employees GROUP BY department_id HAVING AVG(salary)>(SELECT AVG(salary) FROM employees); -- 6.查询出公司中所有 manager的详细信息
SELECT * FROM employees e WHERE e.`employee_id` IN
(SELECT DISTINCT manager_id FROM employees WHERE manager_id IS NOT NULL); -- 7.各个部门中 最高工资中 最低的那个部门的 最低工资是多少
SELECT MIN(salary) FROM employees e WHERE e.`department_id` =
(SELECT department_id FROM employees GROUP BY department_id ORDER BY MAX(salary) ASC LIMIT 1); -- 8.查询平均工资最高的部门的manager的详细信息:last_name ,department_id,email,salary
SELECT last_name,department_id,email,salary FROM employees WHERE employee_id =
(SELECT manager_id FROM departments WHERE department_id =
(SELECT department_id FROM employees GROUP BY department_id ORDER BY AVG(salary) DESC LIMIT 1)) ; -- 简单的
SELECT last_name,d.department_id,email,salary FROM employees e
JOIN departments d
ON d.`manager_id`=e.`employee_id`
WHERE e.`department_id` =
(SELECT department_id FROM employees GROUP BY department_id ORDER BY AVG(salary) DESC LIMIT 1)
9.联合查询
-- 联合查询
/*
union 联合,合并:将多条查询语句的结果合并成一个结果
语法:
查询语句1
union
查询语句2
union
... 应用场景:要查询的结果来自多个表,且多个表没有直接的连接关系,但查询的信息一致时
特点:1.多条查询语句的查询列数是一致的
2.要求多条查询语句的查询的每一列类型和顺序最好一致
3.默认是去重,如果不去重使用union all
*/ -- 查询部门编号>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;
<MySQL>入门一 查询 DQL的更多相关文章
- 【数据库】9.0 MySQL入门学习(九)——获得数据库和表的信息、日期计算、查询、选择特殊列
1.0 SELECT语句用来从数据表中检索信息. SELECT what_to_select FROM which_table WHERE conditions_to_satisfy; what_to ...
- 【数据库】7.0 MySQL入门学习(七)——MySQL基本指令:帮助、清除输入、查询等
1.0 help == ? 帮助指令,查询某个指令的解释.用法.说明等.详情参考博文: [数据库]6.0 MySQL入门学习(六)——MySQL启动与停止.官方手册.文档查询 https://www. ...
- MySQL学习04(DQL查询)
DQL查询 DQL语言 DQL( Data Query Language 数据查询语言 ) 查询数据库数据 , 如SELECT语句 简单的单表查询或多表的复杂查询和嵌套查询 是数据库语言中最核心,最重 ...
- mysql入门与进阶
MySQL入门与进阶 需求:对一张表中的数据进行增删改查操作(CURD) C:create 创建 U:update 修改 R:read 读|检索 查询 D:delete 删除涉及技术:数据库 1.数据 ...
- 21分钟 MySQL 入门教程(转载!!!)
21分钟 MySQL 入门教程 目录 一.MySQL的相关概念介绍 二.Windows下MySQL的配置 配置步骤 MySQL服务的启动.停止与卸载 三.MySQL脚本的基本组成 四.MySQL中的数 ...
- MYSQL入门全套(第三部)
MYSQL入门全套(第一部) MYSQL入门全套(第二部) 索引简介 索引是对数据库表中一个或多个列(例如,employee 表的姓名 (name) 列)的值进行排序的结构.如果想按特定职员的姓来查找 ...
- MySQL入门笔记
MySQL入门笔记 版本选择: 5.x.20 以上版本比较稳定 一.MySQL的三种安装方式: 安装MySQL的方式常见的有三种: · rpm包形式 · 通用二进制 ...
- MySQL入门转载
21分钟 MySQL 入门教程 http://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html 目录 一.MySQL的相关概念介绍 二.Wi ...
- mysql 入门 基本命令
MYSQL入门学习之一:基本操作 1.登录数据库 www.2cto.com 命令:mysql -u username –p (mysql -h主机地址 -u用户名 -p用户密码) ...
随机推荐
- Eclipse-Hadoop-Plugin编译
1 JDK配置 1.1 安装JDK 具体可以百度,网上教程很多,有JAVA开发环境的都是已经安装的. 1.2 配置环境变量 设置JAVA_HOME.CLASSPATH.PATH等.具体可以百度,有JA ...
- Tyvj1474 打鼹鼠
Description 在这个“打鼹鼠”的游戏中,鼹鼠会不时地从洞中钻出来,不过不会从洞口钻进去(鼹鼠真胆大……).洞口都在一个大小为n(n<=1024)的正方形中.这个正方形在一个平面直角坐标 ...
- UML建模 | Rose | 没有跳出可选择新建RUP的对话框解决方法
- Points on Plane Codeforces - 576C
https://www.luogu.org/problemnew/show/CF576C 看题面,一眼按莫队的方法排一下 直接交就会和我一样发现WA掉了... 算一下会发现,上限是3e9(块内左端点1 ...
- Django的filter查询
Django的filter查询 name__contains表示精确大小写的模糊查询 使用name__icontains表示忽略大小写 year_count = DownloadFile.object ...
- Linux--NiaoGe-Service-06
Linux网络排错 思路: 硬件问题: 首先排除硬件故障,包括网线.Hub.Switch.Router.网卡.设备配置规则等等. 软件问题: 1.网卡的IP/Netmask设置错误 IP.Netmas ...
- Azkaban的功能特点(二)
Azkaban是什么?(一) 不多说,直接上干货! http://www.cnblogs.com/zlslch/category/938837.html Azkaban的功能特点 它具有如下功能特点: ...
- 牛客网Java刷题知识点之同步方法和同步代码块的区别(用synchronized关键字修饰)
不多说,直接上干货! 扩展博客 牛客网Java刷题知识点之多线程同步的实现方法有哪些 为何要使用同步? java允许多线程并发控制,当多个线程同时操作一个可共享的资源变量时(如数据的增删改查 ...
- auth_basic 认证
shell > yum -y install httpd-tools # 安装 htpasswd 工具 shell > cd /usr/local/nginx-/conf shell &g ...
- HTTP/1.1 持久连接 persistent connection
首先:HTTP的长连接和短连接本质上是TCP长连接和短连接. 1. 在HTTP1.0中,默认的是短连接,没有正式规定 Connection:Keep-alive 操作:在HTTP1.1中所有连接都是K ...