diff --git a/engine_table.go b/engine_table.go index 87388a355..001d72e7e 100644 --- a/engine_table.go +++ b/engine_table.go @@ -25,13 +25,21 @@ func (engine *Engine) tbNameWithSchema(v string) string { return v } +func isSubQuery(tbName string) bool { + const selStr = "select" + if len(tbName) <= len(selStr)+1 { + return false + } + + return strings.EqualFold(tbName[:len(selStr)], selStr) || strings.EqualFold(tbName[:len(selStr)+1], "("+selStr) +} + // TableName returns table name with schema prefix if has func (engine *Engine) TableName(bean interface{}, includeSchema ...bool) string { tbName := engine.tbNameNoSchema(bean) - if len(includeSchema) > 0 && includeSchema[0] { + if len(includeSchema) > 0 && includeSchema[0] && !isSubQuery(tbName) { tbName = engine.tbNameWithSchema(tbName) } - return tbName } diff --git a/session_query_test.go b/session_query_test.go index 772206a8a..7e72357f7 100644 --- a/session_query_test.go +++ b/session_query_test.go @@ -371,10 +371,18 @@ func TestJoinWithSubQuery(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, 1, cnt) + tbName := testEngine.Quote(testEngine.TableName("join_with_sub_query_depart", true)) var querys []JoinWithSubQuery1 - err = testEngine.Join("INNER", builder.Select("id").From(testEngine.Quote(testEngine.TableName("join_with_sub_query_depart", true))), + err = testEngine.Join("INNER", builder.Select("id").From(tbName), "join_with_sub_query_depart.id = join_with_sub_query1.depart_id").Find(&querys) assert.NoError(t, err) assert.EqualValues(t, 1, len(querys)) assert.EqualValues(t, q, querys[0]) + + querys = make([]JoinWithSubQuery1, 0, 1) + err = testEngine.Join("INNER", "(SELECT id FROM "+tbName+") join_with_sub_query_depart", "join_with_sub_query_depart.id = join_with_sub_query1.depart_id"). + Find(&querys) + assert.NoError(t, err) + assert.EqualValues(t, 1, len(querys)) + assert.EqualValues(t, q, querys[0]) }