Your First JOIN
Your First JOIN
What to Notice
We are able to pull data from two tables:
- orders
- accounts
Above, we are only pulling data from the orders table since in the SELECT statement we only reference columns from the orders table.
The ON statement holds the two columns that get linked across the two tables. This will be the focus in the next concepts.
Additional Information
If we wanted to only pull individual elements from either the orders or accounts table, we can do this by using the exact same information in the FROM and ON statements. However, in your SELECT statement, you will need to know how to specify tables and columns in the SELECT statement
:
- The table name is always before the period.
- The column you want from that table is always after the period.
For example, if we want to pull only the account name and the dates in which that account placed an order, but none of the other columns, we can do this with the following query:
SELECT accounts.name, orders.occurred_at FROM orders JOIN accounts ON orders.account_id = accounts.id;
This query only pulls two columns, not all the information in these two tables. Alternatively, the below query pulls all the columns from both the accounts and orders table.
SELECT * FROM orders JOIN accounts ON orders.account_id = accounts.id;
And the first query you ran pull all the information from only the orders table:
SELECT orders.* FROM orders JOIN accounts ON orders.account_id = accounts.id;
Joining tables allows you access to each of the tables in the SELECT statement through the table name, and the columns will always follow a . after the table name.
Comments
Post a Comment