为什么需要多表查询
1、单表查询在WEB 要经过几次http交互,再不同表之间 才能查找到数据。会浪费很多时间,因此需要多表查询。
2、如果多张表合在一张表中,会导致 会多字段不能充分利率用,浪费存储空间。
3、程序读取的时候会读取过多的多余字段,导致内存浪费。
4、分表更利于并发
多表查询的正确方式
1、多表查询的正确方式:需要有连接条件,如果不加连接条件会产生笛卡儿积错误
2、建议:从sql优化的角度,建议多表查询时,每个字段前都指明其所在的表。
SELECT employee.`name` , dept.name FROM employee,dept WHERE dept.id=employee.dept_id;
3、可以给表起别名,在SELECT和wHERE中使用表的别名。如果给表起了别名,一旦在SELECT或wHERE中使用表名的话,则必须使用表的别名,而不能再使用表的原名。
4、如果有n个表实现多表的查询,则需要至少n-1个连接条件
多表查询 案例
部门
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for dept -- ---------------------------- DROP TABLE IF EXISTS `dept`; CREATE TABLE `dept` ( `id` int NOT NULL, `name` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of dept -- ---------------------------- INSERT INTO `dept` VALUES (1, '研发部'); INSERT INTO `dept` VALUES (2, '市场部'); INSERT INTO `dept` VALUES (3, '财务部'); INSERT INTO `dept` VALUES (4, '销售部'); SET FOREIGN_KEY_CHECKS = 1;
员工
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for employee -- ---------------------------- DROP TABLE IF EXISTS `employee`; CREATE TABLE `employee` ( `id` int NOT NULL, `name` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL, `dept_id` int NOT NULL, `age` int NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE, INDEX `fk_dept_id`(`dept_id` ASC) USING BTREE, CONSTRAINT `fk_dept_id` FOREIGN KEY (`dept_id`) REFERENCES `dept` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of employee -- ---------------------------- INSERT INTO `employee` VALUES (1, '张无忌', 1, 20); INSERT INTO `employee` VALUES (2, '杨逍', 2, 33); INSERT INTO `employee` VALUES (3, '赵敏', 2, 18); INSERT INTO `employee` VALUES (4, '常遇春', 2, 43); SET FOREIGN_KEY_CHECKS = 1;
可以给表起别名,在SELECT和wHERE中使用表的别名。
SELECT emp.employee_id, dept.department_name, emp.department_id FROM employees emp, departments dept WHERE emp. department_idT = dept,department_id;
#如果给表起了别名,一旦在SELECT或wHERE中使用表名的话,则必须使用表的别名,而不能再使用表的原名。
SELECT emp.employee_id, departments.department_name , emp. department_id FROM employees emp , departments dept WHER Eemp .department_id` = departments .department_id; 错误了,因为原名已经被覆盖了,只能使用dept.department_id;
如果有n个表实现多表的查询,则需要至少n-1个连接条件
SELECT e.employee_id,e.last_name,d.department_name,1.city,e.department_id,1.location_id FROM employees e,departments d,locations l WHERE e. "department_idT = d. 'department_id` AND d. " location_id= l.`location_id ;