MySQL DQL(数据查询语言)深度解析与实践
数据查询语言(DQL,Data Query Language)是SQL中用于检索数据库中数据的部分,最核心的命令便是SELECT
语句。MySQL作为广泛应用的关系型数据库,其DQL能力非常强大,支持从简单查询到复杂联接、子查询等多种数据检索方式。本文将详细介绍MySQL中的DQL语法,通过实例代码帮助你掌握数据查询的艺术。
一、基础查询
单表查询
SELECT column1, column2
FROM table_name;
例如,从employees
表中选取所有员工的姓名(name
)和职位(title
):
SELECT name, title
FROM employees;
通配符 *
星号(*)可以用来选择表中的所有列:
SELECT *
FROM employees;
二、条件过滤(WHERE子句)
使用WHERE
子句对查询结果进行筛选:
SELECT column1, column2
FROM table_name
WHERE condition;
假设我们要找到薪资(salary
)超过50000的员工:
SELECT name, salary
FROM employees
WHERE salary > 50000;
三、排序(ORDER BY)
ORDER BY
用于对结果集进行排序:
SELECT column1, column2
FROM table_name
ORDER BY column_name [ASC|DESC];
按照员工薪资降序排序:
SELECT name, salary
FROM employees
ORDER BY salary DESC;
四、分组(GROUP BY)与聚合函数
GROUP BY
用于将结果集按照一个或多个列进行分组,配合聚合函数(如COUNT()
, SUM()
, AVG()
等)使用:
SELECT column, AGGREGATE_FUNCTION(column)
FROM table_name
GROUP BY column;
统计各部门的员工人数:
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
五、HAVING子句
HAVING
子句用于对GROUP BY
后的结果进行过滤:
SELECT column, AGGREGATE_FUNCTION(column)
FROM table_name
GROUP BY column
HAVING condition;
找出平均薪资超过部门平均值的部门:
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING avg_salary > (SELECT AVG(salary) FROM employees);
六、联接查询(JOIN)
联接是将多个表中的行基于某些匹配条件组合起来的过程。MySQL支持多种联接类型,如内联接(INNER JOIN
)、左联接(LEFT JOIN
)等。
内联接
SELECT table1.column, table2.column
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
查询员工姓名和他们所在部门的名称:
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;
左联接
SELECT table1.column, table2.column
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
展示所有员工及其对应的部门,即使某些员工未分配部门:
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;
七、子查询
子查询是嵌套在其他查询中的查询,可以作为条件或数据来源。
SELECT column
FROM table_name
WHERE column IN (SELECT column FROM another_table WHERE condition);
找出薪资高于公司平均薪资的员工:
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);