[TOC]
多表查询
子查询
子查询(Subquery)是一个嵌套在另一个查询中的查询语句
SELECT column1, column2, ...
FROM table_name
WHERE column_name operator (
SELECT column1, column2, ...
FROM another_table
WHERE condition
);
- column1, column2, ...:要查询的列。
- table_name:主查询的表。
- column_name:主查询中用于比较的列。
- operator:比较运算符,如 =, <>, >, <, >=, <=, IN, NOT IN, EXISTS, NOT EXISTS 等。
- another_table:子查询的表。
- condition:子查询的条件
连接查询
内连接
示例
SELECT orders.order_id, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;
小结
- 内连接是将一张表的每一条记录去另外一张表根据条件匹配
- 匹配成功:保留连接的数据
- 匹配失败:都不保留
- 内连接语法:
左表 join 右表 on 连接条件
- 内连接只返回符合条件的行,即两个表中具有相同或匹配值的行
外连接
概念
外连接:outer join,包含左外连接(左连接):left join和右外连接(右连接):right join
左外连接
示例
SELECT *
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
小结
- 左表为主表
- table1 的所有数据都会被包含,而 table2 的数据只有在与 table1 的数据匹配时才会出现
右外连接
示例
SELECT *
FROM table1
RIGHT OUTER JOIN table2 ON table1.column_name = table2.column_name;
小结
- 右连接为主表
- table2 的所有数据都会被包含,而 table1 的数据只有在与 table2 的数据匹配时才会出现
using关键字
示例
SELECT *
FROM table1
JOIN table2 USING (common_column_name);
小结
- 使用 USING 关键字可以避免在ON子句中重复指定连接条件,使查询更加简洁
- 连接查询时如果是同名字段作为连接条件,using可以代替on出现(比on更好)
using(id) == on table1.column_name = table2.column_name;
- THE END -
最后修改:2025年8月1日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://www.qian777.cn/37.html
共有 0 条评论