CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: SQL

T-SQL Tuesday Sample Code

290 Views
Copy Code Show/Hide Line Numbers
   1:  CREATE TABLE table1 (id int);
   2:  INSERT INTO table1 VALUES (1);
   3:  INSERT INTO table1 VALUES (2);
   4:  INSERT INTO table1 VALUES (3);
   5:   
   6:  CREATE TABLE table2 (id int);
   7:  INSERT INTO table2 VALUES (2);
   8:  INSERT INTO table2 VALUES (3);
   9:   
  10:  CREATE TABLE table3 (id int);
  11:  INSERT INTO table3 VALUES (2);
  12:  INSERT INTO table3 VALUES (3);
  13:   
  14:  SELECT table1.id,
  15:         table2.id,
  16:         table3.id
  17:  FROM table1
  18:    LEFT OUTER JOIN
  19:       table2
  20:    INNER JOIN
  21:       table3
  22:       ON table2.id = table3.id
  23:       ON table1.id = table2.id;
  24:   
  25:  SELECT table1.id,
  26:         table2.id,
  27:         table3.id
  28:  FROM table2
  29:    INNER JOIN
  30:       table3
  31:       ON table2.id = table3.id
  32:    RIGHT OUTER JOIN
  33:       table1
  34:       ON table2.id = table1.id;
by Luciano Evaristo Guerche (Gorše)
  January 13, 2010 @ 9:54am
Tags:

by Luciano Evaristo Guerche (Gorše)    January 13, 2010 @ 10:08am

To return only those records on table1 not matching against table2+table3, I'd add a where clause like the one below:

WHERE table2.id IS NULL;

by Luciano Evaristo Guerche (Gorše)    January 13, 2010 @ 9:55am

Results I got when I ran the script:

id id id
----------- ----------- -----------
1 NULL NULL
2 2 2
3 3 3

(3 row(s) affected)

id id id
----------- ----------- -----------
1 NULL NULL
2 2 2
3 3 3

(3 row(s) affected)

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate