SQL Querying Multiple Tables: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 5: Line 5:
=Overview=
=Overview=
More than one table can be used in a <code>[[SQL_SELECT#Querying_Multiple_Tables|FROM]]</code> query clause, and when that happens, it is said that the query performs a '''join'''.
More than one table can be used in a <code>[[SQL_SELECT#Querying_Multiple_Tables|FROM]]</code> query clause, and when that happens, it is said that the query performs a '''join'''.
=Examples=
All examples provided in this article are based on three tables (<code>person</code>, <code>address</code> and <code>country</code>), with the following schema:
<font size=-2>
<b>person</b>
Column    | Type 
-----------+---------
id        | integer  <font color=teal># primary key</font>
name      | text   
company_id | integer  <font color=teal># foreign key that references company(id)</font>
<b>company</b>
Column    | Type 
-----------+---------
id        | integer <font color=teal># primary key</font>
name      | text   
city_id    | integer <font color=teal># foreign key that references city(id)</font>
<b>city</b>
Column    | Type 
-----------+---------
id        | integer <font color=teal># primary key</font>
name      | text   
</font>


=Join Condition=
=Join Condition=

Revision as of 20:24, 23 May 2024

External

Internal

Overview

More than one table can be used in a FROM query clause, and when that happens, it is said that the query performs a join.

Examples

All examples provided in this article are based on three tables (person, address and country), with the following schema:

person 

Column     | Type  
-----------+---------
id         | integer  # primary key
name       | text    
company_id | integer  # foreign key that references company(id)

company

Column     | Type   
-----------+---------
id         | integer # primary key
name       | text    
city_id    | integer # foreign key that references city(id)

city

Column     | Type   
-----------+---------
id         | integer # primary key
name       | text    

Join Condition

If more than one table appears in the FROM clause, then the condition used to link the tables must be included as well. This is the ANSI-approved method. of joining multiple tables, and it is the most portable across various database servers.



Foreign key

Join