Look at this:
SELECT <COLUMNS>
FROM <TABLE1>RIGHT 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: RIGHT JOIN is the same as RIGHT OUTER JOIN
Here is an example:
- 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!');
- INSERT INTO @Passwords
- VALUES (10, 'bad password!');
- -- Right outer join between two table variables.
- SELECT U.firstName, U.lastName, P.[password]
- FROM @UserAccounts AS U RIGHT OUTER JOIN @Passwords AS P
- ON U.acountID = P.acountID;
The results of this query are:
(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)
(1 row(s) affected)
firstName lastName password
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
John Doe password
Jane Doe jane32
Jim Doe Password!
NULL NULL bad password!
(4 row(s) affected)
No comments:
Post a Comment