SQL JOIN UNION

JOIN

join type

  • (INNER) JOIN: Returns records that have matching values in both tables

  • LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the right table

  • RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left table

  • FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

Example

  1. 插入另一张表的某个字段
1
2
3
4
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

执行结果

  1. 合并两张表查询结果,并排序
1
2
3
4
5
SELECT * FROM (
SELECT currency_type, amount, status, created_at, updated_at FROM t_deposit_trans
UNION ALL
SELECT currency_type, amount, status, created_at, updated_at FROM t_withdraw_trans
) trans_table ORDER BY trans_table.created_at DESC;

UNION

UNION 操作符用于合并两个或多个 SELECT 语句的结果集。

请注意,UNION内部的 SELECT语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条SELECT语句中的列的顺序必须相同。

语法

1
2
3
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。

UNION ALL 命令和 UNION 命令几乎是等效的,不过 UNION ALL 命令会列出所有的值。

Example

  1. 合并两个表查询结果
1
2
3
SELECT currency, amount, status, created_at, updated_at FROM deposit
UNION
SELECT currency, amount, status, created_at, updated_at FROM withdraw;

注意,这里不能使用order by

  1. 合并结果,并排序
1
2
3
4
SELECT currency, amount, status, created_at, updated_at FROM deposit
UNION ALL
SELECT currency, amount, status, created_at, updated_at FROM withdraw
ORDER BY created_at DESC;