【mysql】mysql单表查询、多表查询、分组查询、子查询等案例详细解析
以下是针对MySQL单表查询、多表查询、分组查询和子查询的示例代码:
单表查询
-- 查询employees表中所有的记录
SELECT * FROM employees;
多表查询
-- 查询employees和departments表中所有的记录
SELECT * FROM employees, departments;
-- 内连接查询,只查询匹配的记录
SELECT * FROM employees INNER JOIN departments ON employees.department_id = departments.id;
-- 左连接查询,查询左表所有记录及其与右表匹配的记录
SELECT * FROM employees LEFT JOIN departments ON employees.department_id = departments.id;
-- 右连接查询,查询右表所有记录及其与左表匹配的记录
SELECT * FROM employees RIGHT JOIN departments ON employees.department_id = departments.id;
分组查询
-- 查询每个部门的平均薪水
SELECT department_id, AVG(salary) FROM employees GROUP BY department_id;
子查询
-- 查询比部门ID为1的平均薪水高的员工的姓名和薪水
SELECT name, salary FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = 1);
这些示例展示了如何在MySQL中进行基本的数据库查询操作,包括如何连接表、分组数据以及如何嵌套查询。
评论已关闭