Skip to content

Commit

Permalink
Merge pull request #183 from huandu/feature/select-lateral-derived-table
Browse files Browse the repository at this point in the history
Support LATERAL keyword
  • Loading branch information
huandu authored Dec 3, 2024
2 parents 5067ee7 + bc2ceb4 commit c4b67f5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
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
}

0 comments on commit c4b67f5

Please sign in to comment.