Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support LATERAL keyword #183

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions select.go
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,11 @@ func (sb *SelectBuilder) BuilderAs(builder Builder, alias string) string {
return fmt.Sprintf("(%s) AS %s", sb.Var(builder), alias)
}

// LateralAs returns a LATERAL derived table expression wrapping a complex SQL.
func (sb *SelectBuilder) LateralAs(builder Builder, alias string) string {
return fmt.Sprintf("LATERAL (%s) AS %s", sb.Var(builder), alias)
}

// NumCol returns the number of columns to select.
func (sb *SelectBuilder) NumCol() int {
return len(sb.selectCols)
Expand Down
26 changes: 26 additions & 0 deletions select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,3 +388,29 @@ func TestSelectBuilderGetFlavor(t *testing.T) {
flavor = sbClick.Flavor()
a.Equal(ClickHouse, flavor)
}

func ExampleSelectBuilder_LateralAs() {
// Demo SQL comes from a sample on https://dev.mysql.com/doc/refman/8.4/en/lateral-derived-tables.html.
sb := Select(
"salesperson.name",
"max_sale.amount",
"max_sale.customer_name",
)
sb.From(
"salesperson",
sb.LateralAs(
Select("amount", "customer_name").
From("all_sales").
Where(
"all_sales.salesperson_id = salesperson.id",
).
OrderBy("amount").Desc().Limit(1),
"max_sale",
),
)

fmt.Println(sb)

// Output:
// SELECT salesperson.name, max_sale.amount, max_sale.customer_name FROM salesperson, LATERAL (SELECT amount, customer_name FROM all_sales WHERE all_sales.salesperson_id = salesperson.id ORDER BY amount DESC LIMIT 1) AS max_sale
}