Skip to content

Commit c4b67f5

Browse files
authored
Merge pull request #183 from huandu/feature/select-lateral-derived-table
Support LATERAL keyword
2 parents 5067ee7 + bc2ceb4 commit c4b67f5

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

select.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,11 @@ func (sb *SelectBuilder) BuilderAs(builder Builder, alias string) string {
286286
return fmt.Sprintf("(%s) AS %s", sb.Var(builder), alias)
287287
}
288288

289+
// LateralAs returns a LATERAL derived table expression wrapping a complex SQL.
290+
func (sb *SelectBuilder) LateralAs(builder Builder, alias string) string {
291+
return fmt.Sprintf("LATERAL (%s) AS %s", sb.Var(builder), alias)
292+
}
293+
289294
// NumCol returns the number of columns to select.
290295
func (sb *SelectBuilder) NumCol() int {
291296
return len(sb.selectCols)

select_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,3 +388,29 @@ func TestSelectBuilderGetFlavor(t *testing.T) {
388388
flavor = sbClick.Flavor()
389389
a.Equal(ClickHouse, flavor)
390390
}
391+
392+
func ExampleSelectBuilder_LateralAs() {
393+
// Demo SQL comes from a sample on https://dev.mysql.com/doc/refman/8.4/en/lateral-derived-tables.html.
394+
sb := Select(
395+
"salesperson.name",
396+
"max_sale.amount",
397+
"max_sale.customer_name",
398+
)
399+
sb.From(
400+
"salesperson",
401+
sb.LateralAs(
402+
Select("amount", "customer_name").
403+
From("all_sales").
404+
Where(
405+
"all_sales.salesperson_id = salesperson.id",
406+
).
407+
OrderBy("amount").Desc().Limit(1),
408+
"max_sale",
409+
),
410+
)
411+
412+
fmt.Println(sb)
413+
414+
// Output:
415+
// 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
416+
}

0 commit comments

Comments
 (0)