- Treating the SQ as a record source (like a table).
- Treating the SQ as a single value.
In case 1 the SQ should either be in the FROM clause or, sometimes possible put within the In() command.
In case 2 the SQ can be used in place of any other item that returns a value (SELECT; WHERE; HAVING; GROUP BY; etc).
Assume the following structure :
Expand|Select|Wrap|Line Numbers
- Table Name=tblOKData
- ID; Autonumber; PK
- Name; String
Expand|Select|Wrap|Line Numbers
- 1 Bat
- 2 Ball
- 3 Racquet
Expand|Select|Wrap|Line Numbers
- Table Name=tblALLData
- ID; Autonumber; PK
- Name; String
Expand|Select|Wrap|Line Numbers
- 1 Glass
- 2 Cup
- 3 Plate
- 21 Bat
- 22 Ball
- 23 Racquet
Say that we wanted to show the tblAllData.ID for all items whose names match those found in the tblOKData table. We could use an INNER JOIN in this case, but alternatively (necessary to illustrate the point here) we could do it with a SQ.
The code would be :
Expand|Select|Wrap|Line Numbers
- SELECT ID
- FROM tblAllData
- WHERE Name In(SELECT [Name]
- FROM tblOKData)
The simplest form of this is to surround a basic SELECT query in parentheses and rename (AS {Name}).
In this case we want the same effect as the SQL above.
The code would be :
Expand|Select|Wrap|Line Numbers
- SELECT subQ.ID
- FROM (SELECT *
- FROM tblAllData) AS subQ INNER JOIN tblOKData
- ON subQ.Name = tblOKData.Name
We want to select all tblAllData.IDs which are greater than the average value of these IDs.
The code would be :
Expand|Select|Wrap|Line Numbers
- SELECT [ID]
- FROM tblAllData
- WHERE [ID]>(SELECT Avg([ID])
- FROM tblAllData)