MySQL入门 | day02 | 连接查询

连接查询

1、自连接 (同一张表内查询)

-- 查询管理者
USE sql_hr;

SELECT e.employee_id, e.first_name, m.first_name as manage
FROM employees e
JOIN employees m
	ON e.reports_to = m.employee_id 

2、多表连接

USE sql_store;

SELECT o.order_id, o.order_date, c.first_name,  os.name as status
FROM orders o
JOIN customers c
	ON  o.customer_id = c.customer_id
JOIN order_statuses os
	ON o.status = os.order_status_id

练习:查询客户的付款详细信息

USE sql_invoicing;

SELECT c.name, p.date, pm.name as payment_method
FROM payments p 
JOIN clients c 
	ON  p.client_id = c.client_id 
JOIN payment_methods pm
	ON p.payment_method = pm.payment_method_id 

3、复合连接查询

USE sql_store;

SELECT *
FROM order_items o 
JOIN order_item_notes oi
	ON o.order_id = oi.order_id 
	AND o.product_id = oi.product_id

4、外连接

SELECT p.product_id, p.name, oi.quantity
FROM products p
LEFT JOIN order_items oi
	ON  p.product_id = oi.product_id 

5、多表外连接

SELECT 
	o.order_date,
    o.order_id,
    c.first_name,
    sh.name as shipper,
    os.name as status
FROM orders o 
LEFT JOIN customers c
	ON o.customer_id = c.customer_id
LEFT JOIN order_statuses os 
	ON o.status = os.order_status_id
LEFT JOIN shippers sh
	ON o.shipper_id = sh.shipper_id 
ORDER BY status

6、USING子句

只能在不同表中,列的名字完全一样的情况下使用

SELECT *
FROM orders o 
LEFT JOIN customers c
	-- ON o.customer_id = c.customer_id
    USING (c.customer_id)

练习

USE sql_invoicing;

SELECT 
	p.date,
	c.name,
    p.amount,
    pm.name 
FROM payments p
LEFT JOIN clients c
	USING(client_id)
LEFT JOIN payment_methods pm
	ON  p.payment_method = pm.payment_method_id

7、自然连接

自然连接 通过 MySql 自己的判断完成连接过程,不需要指定连接条件。 MySql 会使用表内的,相同的字段,作为连接条件。 自然连接 分为内外之分。

8、交叉连接 (返回笛卡尔积)

SELECT 
	sh.name as shipper,
    p.name as product
FROM shippers sh
CROSS JOIN products p
ORDER BY sh.name

SELECT 
	sh.name as shipper,
    p.name as product
FROM shippers sh, products p
ORDER BY sh.name

9、UNION

SELECT 
	order_id, order_date, 'active' as status
FROM orders
WHERE order_date >= '2019-01-01'
UNION
SELECT 
	order_id, order_date, 'archive' as status
FROM orders
WHERE order_date <= '2019-01-01'

你可能感兴趣的:(mysql,数据库,sql)