Archive for June 20th, 2007

How to do an OUTER JOIN in Query of Queries

Wednesday, June 20th, 2007

ColdFusion Query of Queries does not natively support OUTER JOINs. The following code demonstrates a work around to perform a LEFT OUTER JOIN between two CF queries, QueryA and QueryB.

i.e. To do this;

SELECT *
FROM QueryA
LEFT OUTER JOIN QueryB ON QueryA.ID = QueryB.ID

One can use;

<cfquery name="joinQuery" dbtype="query" >
SELECT *
FROM QueryB
WHERE QueryB.ID = -1
</cfquery>

<cfset QueryAddRow(joinQuery) />

<cfquery name="result" dbtype="query" >
SELECT *
FROM QueryA, QueryB
WHERE QueryA.ID = QueryB.ID

UNION

SELECT QueryA.*, joinQuery.*
FROM QueryA, joinQuery
WHERE QueryA.ID NOT IN (#ValueList(QueryB.ID)#)
</cfquery>

A common use of an OUTER JOIN is to find the non-matching records between two record sets, a so called NULL Based OUTER JOIN.

e.g.

SELECT *
FROM QueryA
LEFT OUTER JOIN QueryB ON QueryA.ID = QueryB.ID
WHERE QueryB.ID IS NULL

This situation can be more efficiently implemented in Query of Queries by using the following technique;

SELECT *
FROM QueryA
WHERE QueryA.ID NOT IN (#ValueList(QueryB.ID)#)

Copyright © 2005, David Beale

  • Valid XHTML 1.0!
  • Valid CSS
  • Level Triple-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0