English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在本教程中,您将学习如何使用SQL右连接从两个表中获取数据。
RIGHT JOIN是与LEFT JOIN完全相反。它返回右表中的所有行以及左表中满足连接条件的行。
右连接是外连接的一种,因此也被称为right outer join。外部联接的其他变体是左联接和完全联接。下维恩图说明了右联接的工作方式。
Attenzione:外部联接是一种联接,它在结果集中包含行,即使要联接的两个表中的行之间可能不匹配。
为了清楚地理解这一点,让我们来看看下面employees和departments表。
+--------+--------------+------------+---------+ | emp_id | emp_name | hire_date | dept_id | +--------+--------------+------------+---------+ | | Ethan Hunt | 2001-05-01 | | | | Tony Montana | 2002-07-15 | | | | Sarah Connor | 2005-10-18 | | | | Rick Deckard | 2007-01-03 | | | 5 | Martin Blank | 2008-06-24 | NULL | +--------+--------------+------------+---------+ | +---------+------------------+ | dept_id | dept_name | +---------+------------------+ | 1 | Administration | | 2 | Customer Service | | 3 | Finance | | 4 | Human Resources | | 5 | Sales | +---------+------------------+ | |
表: employees | 表: departments |
现在,假设您要检索所有部门的名称以及在该部门工作的员工的详细信息。但是,在实际情况下,可能有些部门目前没有员工在工作。好吧,让我们找出答案。
以下语句通过使用通用的dept_id字段将employee和department表连接在一起,检索所有可用部门以及该部门员工的id,名称,雇用日期。
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name FROM employees AS t1 RIGHT JOIN departments AS t2 ON t1.dept_id = t2.dept_id ORDER BY dept_name;
提示:在联接查询中,左边的表是在JOIN子句中最左边出现的表,右边的表是在最右边出现的表。
执行上述命令后,您将获得如下输出:
+--------+--------------+------------+------------------+ | emp_id | emp_name | hire_date | dept_name | +--------+--------------+------------+------------------+ | 2 | Tony Montana | 2002-07-15 | Administration | | NULL | NULL | NULL | Customer Service | | 4 | Rick Deckard | 2007-01-03 | Finance | | 1 | Ethan Hunt | 2001-05-01 | Risorse Umane | | 3 | Sarah Connor | 2005-10-18 | Sales | +--------+--------------+------------+------------------+
Una giusta connessione include tutte le righe della tabella del risultato, indipendentemente dal fatto che la colonna dept_id della tabella dell'impiegato corrisponda o meno, perché puoi vedere chiaramente che anche se il dipartimento non ha dipendenti, includerà anche 'Customer Service'.
Attenzione:Se nella tabella di destra c'è una riga, ma nella tabella di sinistra non c'è corrispondenza, le righe dei risultati delle associazioni conterranno valori NULL di tutte le colonne della tabella di sinistra.