阅读量:0
MySQL数据库关联练习
1. 练习背景
本练习旨在通过实际的数据库操作,加深对MySQL数据库中关联查询(JOIN)的理解和应用,我们将创建两个表,并通过关联这两个表来执行查询。
2. 数据库环境
数据库引擎:InnoDB
数据库版本:MySQL 5.7+
3. 创建表
创建员工表 CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, age INT NOT NULL, department_id INT, FOREIGN KEY (department_id) REFERENCES departments(id) ); 创建部门表 CREATE TABLE departments ( id INT AUTO_INCREMENT PRIMARY KEY, department_name VARCHAR(50) NOT NULL );
4. 插入数据
插入部门数据 INSERT INTO departments (department_name) VALUES ('HR'), ('IT'), ('Finance'), ('Marketing'); 插入员工数据 INSERT INTO employees (name, age, department_id) VALUES ('Alice', 30, 1), ('Bob', 25, 2), ('Charlie', 35, 1), ('David', 40, 3), ('Eve', 28, 4), ('Frank', 22, 2), ('Grace', 33, 3);
5. 关联查询练习
5.1 查询所有员工的姓名和所属部门名称
SELECT e.name AS EmployeeName, d.department_name AS DepartmentName FROM employees e JOIN departments d ON e.department_id = d.id;
5.2 查询所有IT部门的员工信息
SELECT * FROM employees e JOIN departments d ON e.department_id = d.id WHERE d.department_name = 'IT';
5.3 查询所有部门名称以及该部门员工的平均年龄
SELECT d.department_name, AVG(e.age) AS AverageAge FROM employees e JOIN departments d ON e.department_id = d.id GROUP BY d.department_name;
5.4 查询没有员工的部门名称
SELECT d.department_name FROM departments d LEFT JOIN employees e ON d.id = e.department_id WHERE e.id IS NULL;
6. 总结
通过上述练习,我们学习了如何使用JOIN语句进行数据库的关联查询,以及如何通过不同的JOIN类型(如INNER JOIN、LEFT JOIN等)来获取所需的数据,这些技能对于日常的数据库操作和数据查询非常重要。