JOIN 语句的整个目标是一次能够从多个表格中获取数据。
JOIN 使我们能够从多个表格中获取数据。
JOIN 和 ON
JOIN (INNER JOIN)指定了你要从中获取数据的第二个表格。
ON 表示你想如何合并 FROM 和 JOIN 语句中的表格(PK和FK)。
例:尝试从 orders 表格中获取 standard_qty、gloss_qty 和 poster_qty,并从 accounts 表格中获取 website 和 primary_poc。
SELECT orders.standard_qty, orders.gloss_qty,
orders.poster_qty, accounts.website,
accounts.primary_poc
FROM orders
JOIN accounts
ON orders.account_id = accounts.id #PK and FK
PK(主键)与FK(外键)
例:连接多个表格
FROM web_events
JOIN accounts
ON web_events.account_id = accounts.id
JOIN orders
ON accounts.id = orders.account_id
LEFT JOIN and RIGHT JOIN
LEFT JOIN 和 RIGHT JOIN 一样,将FROM 和 JOIN的表格数据翻转一下即可。
一般默认使用LEFT JOIN。
例:
SELECT c.countryid, c.countryName, s.stateName
FROM Country c
LEFT JOIN State s
ON c.countryid = s.countryid;
生成的表格中的列数为3,
生成的表格中的行数为8,
countryid 1 将在生成的表格中出现的次数2,
countryid 6 将在生成的表格中出现的次数1。