SELECT e.employee_id, e.first_name, m.first_name AS manager FROM employees e JOIN employees m ON e.reports_to = m.employee_id
1.3 多表连接
1 2 3 4 5 6 7 8 9 10 11 12 13
USE sql_store;
SELECT o.order_id, o.order_date, c.first_name, c.last_name, os.name ASstatus FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN order_statuses os ON o.status = os.order_status_id
SELECT * FROM order_items oi JOIN order_item_notes oin ON oi.order_id = oin.order_id AND oi.product_id = oin.product_id
1.5 隐式连接语法
1 2 3 4 5 6 7 8 9 10
SELECT * FROM orders o JOIN customers c ON o.customer_id = c.customer_id
-- Implicit Join Syntax SELECT * FROM orders o, customers c WHERE o.customer_id = c.customer_id
不建议使用隐式连接语法,要是忘写WHERE就完了。
2 外连接
1 2 3 4 5 6 7 8
SELECT c.customer_id, c.first_name, o.order_id FROM customers c RIGHTJOIN orders o ON c.customer_id = o.customer_id ORDERBY c.customer_id
LEFT (OUTER) JOIN 和 RIGHT (OUTER) JOIN, OUTER 可省略
2.1 多表外连接
1 2 3 4 5 6 7 8 9 10 11
SELECT c.customer_id, c.first_name, o.order_id, sh.name AS shipper FROM customers c LEFTJOIN orders o ON c.customer_id = o.customer_id LEFTJOIN shippers sh ON o.shipper_id = sh.shipper_id ORDERBY c.customer_id
2.2 自外连接
1 2 3 4 5 6 7 8 9
USE sql_hr;
SELECT e.employee_id, e.first_name AS employee, m.employee_id AS manager FROM employees e LEFTJOIN employees m ON e.reports_to = m.employee_id
3 USING子句
使用于两张表的键名完全一致的情况
1 2 3 4 5 6 7 8 9 10
SELECT o.order_id, c.first_name, sh.name AS shipper FROM orders o JOIN customers c -- ON o.customer_id = c.customer_id USING (customer_id) LEFTJOIN shippers sh USING (shipper_id)
1 2 3 4 5 6
SELECT * FROM order_items oi JOIN order_item_notes oin -- ON oi.order_id = oin.order_id -- AND oi.product_id = oin.product_id USING (order_id, product_id)
4 自然连接
自动找到同名的column来连接。(容易出错,不建议使用)
1 2 3 4 5
SELECT o.order_id, c.first_name FROM orders o NATURALJOIN customers c
5 交叉连接
连接两张表的所有records
1 2 3 4 5 6
SELECT c.first_name AS customers, p.name AS product FROM customers c CROSSJOIN products p ORDERBY c.first_name
应用场景:表一是大中小型号,表二是红黄蓝等各种颜色,将所有型号和所有颜色组合起来。
隐式语法
1 2 3 4 5
SELECT c.first_name AS customers, p.name AS product FROM customers c, products p ORDERBY c.first_name
6 联合(Unions)
筛选某些records,用union将多次筛选的结果联合起来
1 2 3 4 5 6 7 8 9 10 11 12 13
SELECT order_id, order_date, 'Active'ASstatus FROM orders WHERE order_date >= '2019-01-01'-- 在此日期后的order, 状态设为active UNION SELECT order_id, order_date, 'Archived'ASstatus-- 在此日期前的order, 状态设为archived FROM orders WHERE order_date < '2019-01-01'
也可以联合多张表
1 2 3 4 5
SELECT first_name -- 决定列名 FROM customers UNION SELECTname FROM shippers
SELECT customer_id, first_name, points, 'Bronze'AStype FROM customers c WHERE points < 2000 UNION SELECT customer_id, first_name, points, 'silver'AStype FROM customers c WHERE points BETWEEN2000AND3000 UNION SELECT customer_id, first_name, points, 'Gold'AStype FROM customers c WHERE points > 3000 ORDERBY first_name