[MySQL] MySQL复合查询(多表查询、子查询)
-- 创建数据库和表
CREATE DATABASE IF NOT EXISTS compound_queries;
USE compound_queries;
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(id)
);
CREATE TABLE departments (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50)
);
CREATE TABLE locations (
id INT PRIMARY KEY AUTO_INCREMENT,
street_address VARCHAR(100),
postal_code VARCHAR(10),
city VARCHAR(50),
location_type VARCHAR(50)
);
-- 插入示例数据
INSERT INTO departments (name) VALUES ('HR'), ('IT'), ('Sales');
INSERT INTO locations (street_address, postal_code, city, location_type) VALUES
('123 Main St', '12345', 'Cityville', 'Headquarters'),
('456 Main St', '45678', 'Townville', 'Regional Office');
INSERT INTO employees (name, department_id) VALUES
('John Doe', 1),
('Jane Smith', 1),
('Mike Brown', 2),
('Anna Black', 3);
-- 多表查询: 查询员工及其部门信息
SELECT e.name, d.name AS department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;
-- 子查询: 查询员工数量最多的部门
SELECT d.name, COUNT(e.id) AS employee_count
FROM departments d
JOIN employees e ON e.department_id = d.id
GROUP BY d.name
ORDER BY employee_count DESC
LIMIT 1;
这个例子展示了如何在MySQL中创建数据库和表,以及如何使用多表查询和子查询来获取所需的信息。这对于学习复杂查询和数据关系管理是一个很好的起点。
评论已关闭