From 7a6b1361cc86b4cc2a7196c26366a1eea5ea2c70 Mon Sep 17 00:00:00 2001 From: u Date: Fri, 10 Feb 2023 18:04:48 +0800 Subject: [PATCH] 'fix' --- types.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/types.go b/types.go index 3032715..372833f 100644 --- a/types.go +++ b/types.go @@ -406,8 +406,10 @@ func (q *Query) FromSelect(selectStmt *sqlparser.Select) error { for _, v := range selectStmt.SelectExprs { switch expr := v.(type) { case *sqlparser.StarExpr: + // log.Println("selectStmt.StarExpr", reflect.TypeOf(expr), jsonEncode(expr)) q.Fields = append(q.Fields, Field{ - Name: "*", + Name: "*", + FromTable: expr.TableName.Name.String(), }) case *sqlparser.AliasedExpr: // log.Println("selectStmt.AliasedExpr", reflect.TypeOf(expr.Expr), jsonEncode(expr.Expr)) @@ -446,10 +448,19 @@ func (q *Query) FromSelect(selectStmt *sqlparser.Select) error { switch form := form.(type) { case *sqlparser.AliasedTableExpr: //未联表 - q.From.Table = string(form.Expr.(sqlparser.TableName).Name.String()) if form.As.String() != "" { q.From.As = form.As.String() } + switch exp := form.Expr.(type) { + case sqlparser.TableName: + q.From.Table = string(exp.Name.String()) + case *sqlparser.Subquery: + subQuery := &Query{} + if err := subQuery.FromSelect(exp.Select.(*sqlparser.Select)); err != nil { + return err + } + q.From.SubQuery = subQuery + } case *sqlparser.JoinTableExpr: //有联表 //确定主表 @@ -738,8 +749,5 @@ func (q *Query) ToSql() (string, error) { return "", fmt.Errorf("failed to build query: %w", err) } - buf := builder.NewWriter() - b.WriteTo(buf) - log.Println("NewWriter:", buf.String()) return b.ToBoundSQL() }