分别实现单表查询、不带分组过滤条件的分组查询、带分组过滤条件的分组查询、单表自身连接查询、两表连接查询、三表连接查询、视图的查询等查询操作。
时间: 2024-10-20 15:14:34 浏览: 15
MySql基本查询、连接查询、子查询、正则表达查询讲解
在数据库查询中,有多种类型的查询操作:
1. **单表查询**:这种最基础的查询通常只涉及一张表,如查找所有员工的信息,SQL语句可能是这样的:
```sql
SELECT * FROM employees;
```
2. **不带分组的简单分组查询**:如果需要按某个字段进行分类计数,比如统计每个部门有多少员工,可以这样写:
```sql
SELECT department, COUNT(*) as employee_count FROM employees GROUP BY department;
```
3. **带分组过滤条件的分组查询**:例如找出销售额超过一定金额的所有产品类别,加上HAVING子句:
```sql
SELECT category, SUM(sales) as total_sales FROM products GROUP BY category HAVING SUM(sales) > 100000;
```
4. **单表自身连接查询**:用于查找满足某种关联关系的数据,如查找员工与其直接上级的关系:
```sql
SELECT e1.name as employee_name, e2.name as manager_name FROM employees e1 JOIN employees e2 ON e1.manager_id = e2.id;
```
5. **两表连接查询**:连接两个表基于共享的键值,如用户订单数据:
```sql
SELECT users.name, orders.product FROM users INNER JOIN orders ON users.id = orders.user_id;
```
6. **三表连接查询**:如果有多张表需要关联,例如员工、部门和项目,可能会用到嵌套的JOIN:
```sql
SELECT emp.name, dep.name, proj.name FROM employees emp JOIN departments dep ON emp.dept_id = dep.id JOIN projects proj ON emp.project_id = proj.id;
```
7. **视图查询**:先创建视图将复杂查询结果抽象,然后对视图进行查询简化操作,如创建一个包含销售员总销售额的视图:
```sql
CREATE VIEW top_sellers AS SELECT salesperson, SUM(amount) as total_sales FROM sales GROUP BY salesperson;
SELECT * FROM top_sellers WHERE total_sales > 100000;
```
阅读全文