-- 示例代码:MySQL 连表查询
-- 假设有两个表:`orders` 和 `customers`
-- `orders` 表包含订单信息,`customers` 表包含客户信息
-- 我们可以通过 `customer_id` 字段将这两个表连接起来
-- 1. 内连接 (INNER JOIN) 查询:只返回两个表中匹配的记录
SELECT orders.order_id, customers.customer_name, orders.order_date
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id;
-- 解释:上述查询会返回所有订单及其对应的客户信息。只有当 `orders` 表中的 `customer_id` 在 `customers` 表中存在时,才会返回该记录。
-- 2. 左连接 (LEFT JOIN) 查询:返回左表中的所有记录,即使右表中没有匹配项
SELECT orders.order_id, customers.customer_name, orders.order_date
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id;
-- 解释:上述查询会返回所有的订单信息,即使某些订单没有对应的客户信息(即 `customer_name` 可能为 NULL)。
-- 3. 右连接 (RIGHT JOIN) 查询:返回右表中的所有记录,即使左表中没有匹配项
SELECT orders.order_id, customers.customer_name, orders.order_date
FROM orders
RIGHT JOIN customers ON orders.customer_id = customers.customer_id;
-- 解释:上述查询会返回所有的客户信息,即使某些客户没有下过订单(即 `order_id` 可能为 NULL)。
-- 4. 全外连接 (FULL OUTER JOIN) 查询:返回两个表中的所有记录,无论是否匹配
-- 注意:MySQL 不直接支持 FULL OUTER JOIN,但可以通过 UNION 来实现
SELECT orders.order_id, customers.customer_name, orders.order_date
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id
UNION
SELECT orders.order_id, customers.customer_name, orders.order_date
FROM orders
RIGHT JOIN customers ON orders.customer_id = customers.customer_id;
-- 解释:上述查询会返回所有订单和客户的信息,无论是否有匹配项。
上一篇:进入mysql
下一篇:mysql求和
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站