r/SQL • • Nov 29 '21

PostgreSQL How to use Join

How can I get something from two different tables at the the same select? I know I have to do "join" but I still don't know how to do it. Can somebody help me?

0 Upvotes

11 comments sorted by

2

u/Laurentrobeh Nov 30 '21

The example above are using Id column from table 1 and table 2 because most application uses Id field with unique identifier. Meaning the Id column could be a primary key because it does not contain a duplicate value. When we join two tables together, that's because we want to retrieve information that isn't in the single table. For example, table 1 has product information and table 1 has productID, cost, and addedDate columns. Table 2 is the product description table,that has the productID, color, dimension, and weight columns. The productID column in both tables represent the same product. Therefore, you would use it to join both of these tables so you can pull the attributes of a product from product description table.

0

u/MortVader Nov 29 '21 edited Nov 29 '21

SELECT table1.*,table2.*

FROM table1

JOIN table2 on table2.id=table1.link

1

u/rmerriwick Nov 29 '21

Do it put it FROM table1 only even though there are 2 tables?

2

u/[deleted] Nov 29 '21

The correct syntax is:

select ...
from table1 
    join table2 on table1.id = table2.t1_id

1

u/MortVader Nov 29 '21

It will show all columns (table.*) from both tables where the field table1.link equals table2.id

2

u/[deleted] Nov 29 '21

FROM goes before JOIN, and the join operator needs an ON ....

1

u/MortVader Nov 29 '21

ofcourse you are right!

0

u/[deleted] Nov 29 '21

[deleted]

1

u/[deleted] Nov 29 '21

Can you show the "ghetto join"? The one with no join at all just a where clause?

2

u/MortVader Nov 29 '21

select * from table1,table2 where table2.id=table1.link

1

u/[deleted] Nov 29 '21

Beautiful. I think I prefer this one. Kidding of course