Monday, December 11, 2006

LEFT JOIN

The LEFT JOIN returns all the rows from the first table even if there is not a match in the second table. Let say Stan has ordered 3 things and Sally none. You will have 4 rows because you will get the 3 things Stan ordered and you will also get a column for Sally even though she is not in the orders table. However, you will not get anything that Ken ordered because he is not in the first table.

Example Code:
CREATE TABLE Person (IDIs int, NameIs varchar(20));
INSERT INTO Person VALUES (1,'stan');
INSERT INTO Person VALUES (2,'Sally');
--INSERT INTO Person VALUES (3, 'Ken');
CREATE TABLE Orders (OIDIs int, PIDIs int, WhatIs varchar(20));
INSERT INTO Orders VALUES (1, 1, 'Moon');
INSERT INTO Orders VALUES (2, 1, 'Sun');
INSERT INTO Orders VALUES (3, 1, 'Stars');
INSERT INTO Orders VALUES (4, 3, 'Dog');
INSERT INTO Orders VALUES (5, 3, 'Cat');
INSERT INTO Orders VALUES (6, 3, 'Car');
SELECT Person.NameIs, Orders.WhatIs FROM Person
LEFT JOIN Orders
ON Person.IDIs=Orders.PIDIs;

No comments: