Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to join tables based on one field?

Author  Topic 

deanglen
Yak Posting Veteran

65 Posts

Posted - 2012-09-05 : 07:56:24
Hi

I have two SQl tables that I want to join together based on a SKU value.

How would I do this? Do I use Join or Inner Join?

But what I do want to have at the end is all the fields from both tables together but linked via the SKU field. Is this possible?



sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-09-05 : 08:10:21
You would use INNER JOIN if you wanted to only get rows for those SKU's that were present in both tables.

LEFT JOIN (or RIGHT JOIN) lets you get the data that is in one table regardless of whether it is in the other table

FULL JOIN lets you get the rows that is in either table.

Take a look at this page and couple of pages linked to it. They explain it with examples much better than I can: http://www.w3schools.com/sql/sql_join_inner.asp
Go to Top of Page

deanglen
Yak Posting Veteran

65 Posts

Posted - 2012-09-05 : 08:16:03
Thanks got it working using this

SELECT *
FROM Product
INNER JOIN ProductVariant
ON Product.ProductID = ProductVariant.ProductID;
Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-09-05 : 08:20:05
Cool! I have couple of comments:

1. In general, experts recommend that you explicitly list the columns that you want to retrieve (and only those columns you do want).

2. People very often use aliases for table names to make it a little bit more readable (and in some cases you are required to use aliases although not in this specific case.
SELECT p.Col1, p.Col2, pv.ColA, pv.ColB
FROM Product AS p
INNER JOIN ProductVariant AS pv
ON p.ProductID = pv.ProductID;
Go to Top of Page
   

- Advertisement -