jaypipes / sqlb

A library for efficiently generating SQL expressions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support subselects in the SELECT clause (scalar subselects)

jaypipes opened this issue · comments

This SQL:

SELECT id, name, (SELECT COUNT(*) FROM t2 WHERE t2.id = t1.id) AS t2_count
FROM t1;

has a subselect in the SELECT clause, which is sometimes called a scalar subselect.

We'd like to support this query construct naturally, so perhaps something like this calling convention might work:

t1 := meta.Table("t1")
t2 := meta.Table("t2")

ss := sqlb.Select(t2.Count()).Where(sqlb.Equal(t1.Column("id"), t2.Column("id"))
s := sqlb.Select(t1.Column("id"), t1.Column("name"), ss.Scalar())

One might think we could just do:

s := sqlb.Select(t1.Column("id"), t1.Column("name"), ss)

however because the behaviour of sqlb.Select() is to consider sqlb.SelectQuery structs supplied as parameters to be derived tables and not scalar subqueries, we need a way of saying that the intent is to use the subquery in the SELECT clause and not the FROM clause. Thus the need for the sqlb.SelectQuery.Scalar() function.