go-sqlbuilder
go-sqlbuilder copied to clipboard
How to write SELECT EXISTS queries?
I am attempting build a query of the form
SELECT EXISTS (SELECT 1 FROM table WHERE ... )
Without resorting to writing raw sql using sb.SQL(), is there some way I can incorporate the builder syntax.
When I try
sb.Select().Exists(sqlbuilder.Select("1").From("table").Where(sb.Equal("col",val )))
I see EXISTS ($1) as the output, instead of SELECT EXISTS .... What am I doing wrong?
The sb.Exists() is derived from Cond, which is designed to build WHERE conditions, not SELECT columns. If you really want to use it as SELECT column, you need to call Select(sb.Exists(...)) to make it work.
Here is a sample.
package main
import (
"fmt"
"github.com/huandu/go-sqlbuilder"
)
func main() {
// Build sub-SELECT query.
val := 1
sub := sqlbuilder.Select("1").From("table")
sub.Where(sub.Equal("col", val))
// Builder for SELECT EXISTS(...).
sb := sqlbuilder.NewSelectBuilder()
sb.Select(sb.Exists(sub))
sql, args := sb.Build()
fmt.Println(sql)
fmt.Println(args)
}