SQL Expressions: Subqueries
Subqueries are queries nested inside another query.
They are just another Table that you can SELECT from.
sq.SelectOne().
From(sq. // <-- subquery
Select(tbl.COLUMN_1).
From(tbl).
Where(tbl.COLUMN_2.Eq(tbl.COLUMN_3)).
Subquery("subquery")
)
If you want to reference a subquery's child columns, you must first assign it to a variable:
subquery := sq.Select(tbl.COLUMN_1).
From(tbl).
Where(tbl.COLUMN_2.Eq(tbl.COLUMN_3).
Subquery("subquery")
sq.Select(subquery["column_1"]).From(subquery)
Equivalent SQL:
SELECT subquery.column_1 FROM (
SELECT tbl.column_1
FROM tbl
WHERE tbl.column_2 = tbl.column_3
) AS subquery;
If you reference a column that doesn't actually exist in the subquery, the column will show up as :blank:
in the generated SQL:
subquery := sq.Select(tbl.COLUMN_1).
From(tbl).
Where(tbl.COLUMN_2.Eq(tbl.COLUMN_3).
Subquery("subquery")
sq.Select(subquery["column_xyz"]).From(subquery)
Equivalent SQL:
SELECT :blank: FROM (
SELECT tbl.column_1
FROM tbl
WHERE tbl.column_2 = tbl.column_3
) AS subquery;