Left table? Right table? What?! If the idea of a left and right table is confusing to you, do not be discouraged. It is not too horrible to figure out. The left table is generally the table listed first, and you guessed it, the right table is generally the table listed second.
Look at this:
SELECT <COLUMNS>
FROM <TABLE1>LEFT JOIN <TABLE2>
ON <TABLE1>.<COLUMN> = <TABLE2>.<COLUMN>
In the above sample, <TABLE1> is the left table and <TABLE2> is the right table.
In this line:
ON <TABLE1>.<COLUMN> = <TABLE2>.<COLUMN>
<COLUMN> is the name of the column that is similar, the column that will be used for matching.
Note: LEFT JOIN is the same as LEFT OUTER JOIN
And here is an example that you can run yourself to see the results:
- USE master;
- GO
- -- Create our first table variable to hold user accounts.
- DECLARE @UserAccounts TABLE
- (
- acountID INT
- , firstName VARCHAR(50)
- , lastName VARCHAR(50)
- );
- -- Create our second table variable to hold our user account passwords.
- DECLARE @Passwords TABLE
- (
- acountID INT
- , [password] VARCHAR(50)
- );
- -- Insert some records into our UserAccounts table variable.
- INSERT INTO @UserAccounts
- VALUES (1, 'John', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (2, 'Jane', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (3, 'Jim', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (4, 'Jimmy', 'Doe');
- INSERT INTO @UserAccounts
- VALUES (5, 'Fonda', 'Doe');
- -- Insert some records into our Passwords table variable.
- INSERT INTO @Passwords
- VALUES (1, 'password');
- INSERT INTO @Passwords
- VALUES (2, 'jane32');
- INSERT INTO @Passwords
- VALUES (3, 'Password!');
- -- Left outer join between two table variables.
- SELECT U.firstName, U.lastName, P.[password]
- FROM @UserAccounts AS U LEFT OUTER JOIN @Passwords AS P
- ON U.acountID = P.acountID;
This query will produce the following result:
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
firstName lastName password
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
John Doe password
Jane Doe jane32
Jim Doe Password!
Jimmy Doe NULL
Fonda Doe NULL
(5 row(s) affected)
No comments:
Post a Comment